The reduce function works as a for loop, where a variable (acc) gets set at every iteration:
The first two examples you gave:
var a = [2,4,5,6,7]
a.reduce((acc,cur,i) => acc, [])
a.reduce((acc,cur,i) => acc, [0, 2])
Are equivalent to assigning the accumulator to itself at each iteration:
var acc = []; // [0, 2] in the second one
for(var i=0; i < a.length; i++){
acc = acc;
}
Whereas your last example:
a.reduce((acc,cur,i) => acc[0], [0, 2])
Is equivalent to assigning to acc its first value at each iteration:
var acc = [0, 2];
for(var i = 0; i < a.length; i++){
acc = acc[0];
}
Each iteration will assign to acc its first value.
The first iteration will look like this:
acc = [0, 2];
i = 0
acc = acc[0] // 0;
The second iteration will then look like this:
acc = 0;
i = 1
acc = acc[0] // undefined;
Now acc has been assigned the value undefined as there is no such property 0 in the value held by acc.
The third iteration will, therefore, look like this:
acc = undefined;
i = 2;
acc = acc[0]; // Error, no property '0' of undefined.
acc = [0, 2]you return0(the number). Second iterationacc = 0accfor next iteration, so when you doacc[0] which is 0so on next iteration you're doing0[0]which returns undefined and thenundefined[0]is syntax error0[0]is fine - it producesundefined. Next iteration there us a TypeError because ofundefined[0]