Q:

Reduce returns undefined

I have an Array of Objects (Cars) :
var car = [
   {speed: 20, color: "red"},
   {speed: 5, color: "blue"},
   {speed: 80, color: "yellow"},
   {speed: 79, name: "orange"}
];

and a function that should return the fastest Car in the Array :
function getFastestCar(cars) {
   cars.reduce(function (prevFastestCar,curFastestcar) {
       if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar;
       else return prevFastestCar;
   }, {speed: -Infinity, name: "test"});
};

After searching for a few hours I couldn´t find any solution why the function is returning undefined. I debugged the code and the function works perfectly fine, except in the last "step" it somehow replaces the fastest Car with undefined. I´m trying to understand the concept behind the reduce Method I know that there are easier ways to do this, but I´m curious why it is not working correctly.

A:

You need to return the reduced value from the function.
return cars.reduce(..);
See the description of reduce.

Return value
The value that results from the reduction.

