JavaScript .reduce, previousValue is always undefined

javascript

Solution

You need to return a value in order to use `reduce` correctly. The returned value will be used in the next step.

Like:

[0,1,2,3,4].reduce(function(previousValue, currentValue) {
     return previousValue + currentValue;
});
// returns 10 in total, because
// 0 + 1 = 1 -> 1 + 2 = 3 -> 3 + 3 = 6 -> 6 + 4 = 10  

Problem

I am curious as to why previousValue is always undefined in the following code when using .reduce on an array: Code: ``` [2,2,2,3,4].reduce(function(previousValue, currentValue){ console.log("Previous Value: " + previousValue); console.log("Current Value: " + currentValue); },0) ``` Output: ``` Previous Value: 0 (index): Current Value: 2 (index): Previous Value: undefined (index): Current Value: 2 (index): Previous Value: undefined (index): Current Value: 2 (index): Previous Value: undefined (index): Current Value: 3 (index):24 Previous Value: undefined (index):23 Current Value: 4 ``` A fiddle can be found here: http://jsfiddle.net/LzpxE/

Original source