Why Array.prototype.push() doesn't work

Hi, when i learn’t about how to flatten an array with the reduce method, i made a mistake of using push instead of concat. It resulted in an error: array.push is not a function – then i didn’t have much understanding of prototype methods . I ignored.

Now that i am fairly used to some concepts about prototypes, i made the same mistake again, got the same error. And that has prompted me to want to know why i am getting that error with array.push(). I think that since the accumulator is an array and it has that method in its prototype i shouldn’t get an error. Instead i should get a different result.

Here is what i tried:

[[0], [3], 1 ,3].reduce((acc, curr) => {
console.log(acc.__proto__, Object.getPrototypeOf(acc)) // .push is present in the methods
return acc.push(curr) // Error: acc.push is not a function

, []) // acc is in fact an array from onset

I will be happy if someone could explain what happened with the code.

You are returning the return value of Array.prototype.push which is not an array. Calling Array.prototype.push on an array instance doesn’t return the mutated Array. It returns the length of the mutated array. Instead do the following:

return acc

Read more about it at MDN.
The first sentence in the documentation says,

The push() method adds one or more elements to the end of an array and returns the new length of the array.


Thank you so much. I didn’t know that the return value of .push is the length of the array.