Can someone please help me understand whats going on here?
let firstArray = [];
firstArray.push(1);
firstArray.push(1);
firstArray.push(1);
console.log("firstArray", firstArray); // result [ 1, 1, 1 ] - as expected.
let secondArray = [1, 2, 3].reduce((acc, item) => {
console.log("acc", acc);
console.log("typeof acc", typeof acc);
// on first passing, the accumulator (acc) is Array[] == object.
// on the second passing the acc == number.
// but why?
/// i expect to get [1,1,1] as my secondArray.
return acc.push(1);
}, []);
console.log("secondArray", secondArray);
the program crashes with "acc.push is not a function"
And inspecting the first logged accumulator
shows that we have the push method - it's a real function:
The return value of Array#push
is the new length of the array after the push. This means that in the second iteration acc
is a number, which doesn't have the push method.
The fix is simple - separate the push and return statements:
const secondArray = [1, 2, 3].reduce((acc, item) => {
acc.push(1);
return acc;
}, []);
console.log(secondArray);