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?