Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript reduce behavior with/without an initial value

Tags:

javascript

I am trying to sum the squares of numbers of an array by JavaScript reduce function. But the result differs when reduce method is called with or without the initial value.

var x = [75, 70, 73, 78, 80, 69, 71, 72, 74, 77];
console.log(x.slice().reduce((ac,n) => ac+(n*n))); // 49179
console.log(x.slice().reduce((ac,n) => ac+(n*n),0)); // 54729

This should be equivalent to the calls above:

console.log(x.slice().map(val => val*val).reduce((ac,n) => ac+n)); // 54729

In this case however both method returns the same value.

console.log([1,2,3].slice().reduce((ac,z) => ac+(z*z))); // 14
console.log([1,2,3].slice().reduce((ac,z) => ac+(z*z), 0)); // 14

Why are the results of the first two calls different and the last two the same?

like image 358
VinArrow Avatar asked Jun 12 '18 22:06

VinArrow


People also ask

Does reduce work on an empty array?

The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements.

How do you handle a reduce on an empty array?

These problems can be solved in two different ways. One way is to actually provide an initialValue as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.

What happens if the initial value of accumulator is not provided in the reduce function explain with an example?

If no initial value is provided, reduce() calls the callback function on each element in the array after the first element.

What does .reduce do in JavaScript?

reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.


1 Answers

If you don't provide the second parameter to .reduce(), it uses the first element of the array as the accumulator and starts at the second element.

In the first example, your first result of the .reduce() iteration is

75 + 70 * 70

while in the second version where pass in an explicit 0 it's

0 + 75 * 75

The cascade of computations from that leads to different results.

In the second example, you'll end up computing

1 + 2 * 2

and then

5 + 3 * 3

in the first line, which gives 14. In the second version, when you start with 0, you'll compute

0 + 1 * 1
1 + 2 * 2
5 + 3 * 3

which is also 14.

like image 142
Pointy Avatar answered Oct 07 '22 23:10

Pointy