12

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?

1 Answer 1

31

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see. So it would skip the call to (n*n). That makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.