 initialValue when using arr.reduce method

Apologies if this question seems a bit silly. I’m in the middle of a project and there’s one line I can’t make sense of right now

function minSum(arr) {
return arr.reduce((acc,curr,index) => acc += curr * arr[arr.length - index - 1])
//.reduce((acc,curr,index) => acc += curr * arr[arr.length - index - 1], 0)
}
console.log(minSum([5,4,2,3]))

this returns 36 (5x3 + 4x2 + 2x4 + 4x5) however when the commented line is used instead, with 0 as initial value, 46 is returned instead. Why is this? Where is 0 thrown in the calculation?

Hello!

That’s because when no initial value is provided, the first element of the array is used at the initial value. In this case, you would start with 5.

Take a look at what the MDN says:

The first time that the callback is run there is no “return value of the previous calculation”. If supplied, an initial value may be used in its place. Otherwise array element 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

2 Likes

Hello

Thank you for your response, I really appreciate it.

I understand that when no initial value is given, the first element is selected and the calculation is simply as I mentioned above. However, what would the calculation be if an initial value of 0 is specified? I can’t see how it would increase the final value by 10.

Adding the starting value will make the reduce run an extra time. The starting value might be zero but the rest of the values are not.

I would suggest you log out all the values inside the reduce.

Code example
// with starting value
function minSum(arr) {
return arr.reduce((acc, curr, index) => {
console.log(arr[arr.length - index - 1]); // 3, 2, 4, 5
console.log(acc); // 0, 15, 23, 31
console.log(curr); // 5, 4, 2, 3
return (acc += curr * arr[arr.length - index - 1]);
}, 0);
}
console.log(minSum([5, 4, 2, 3])); // 46

5 * 3 + 0;  // 15
4 * 2 + 15; // 23
2 * 4 + 23; // 31
3 * 5 + 31; // 46
// without starting value
function minSum(arr) {
return arr.reduce((acc, curr, index) => {
console.log(arr[arr.length - index - 1]); // 2, 4, 5
console.log(acc); // 5, 13, 21
console.log(curr); // 4, 2, 3
return (acc += curr * arr[arr.length - index - 1]);
});
}
console.log(minSum([5, 4, 2, 3])); // 36

4 * 2 + 5;  // 13
2 * 4 + 13; // 21
3 * 5 + 21; // 36
2 Likes

Incredibly helpful. Thank you so much.