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/
Implicitly, without return statement, a JavaScript function returns undefined. A function that doesn’t have return statement implicitly returns undefined: square () function does not return any computation results. The function invocation result is undefined.
The final result of running the reducer across all elements of the array is a single value. Perhaps the easiest-to-understand case for reduce () is to return the sum of all the elements in an array.
Undefined value primitive value is used when a variable has not been assigned a value. The standard clearly defines that you will receive undefined when accessing uninitialized variables, non-existing object properties, non-existing array elements, and alike.
You get undefined when accessing an array element with an out of bounds index. colors array has 3 elements, thus valid indexes are 0, 1, and 2. Because there are no array elements at indexes 5 and -1, the accessors colors [5] and colors [-1] are undefined. In JavaScript, you might encounter so-called sparse arrays.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With