Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript .reduce, previousValue is always undefined

Tags:

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/

like image 495
Jacob Clark Avatar asked Feb 05 '14 22:02

Jacob Clark


People also ask

How do you return undefined from a function in JavaScript?

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.

What is the final result of a reducer in JavaScript?

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.

What is undefined value in C++?

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.

Why do I get undefined when accessing an array element?

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.


1 Answers

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  
like image 97
dersvenhesse Avatar answered Sep 20 '22 11:09

dersvenhesse