"I'm trying to use the concat()
method in JavaScript to merge an object and several numbers into a new array. Here's the code I'm using:
console.log(Array.concat({}, 1, 2, 3));
When I run this code, I get the following error message:
TypeError: Array.concat is not a function
However, when I use Array.prototype.concat.call()
, it works as expected:
console.log(Array.prototype.concat({}, 1, 2, 3));
Why does Array.concat()
cause an error, but Array.prototype.concat.call()
works?"
Not a huge expert, but you might want to review:
In your terminal, web console, if you type Array.prototype, it will basically create an empty array with all of the methods for an array for you, so 'Array.prototype' is an array.
So,
Array.prototype.concat({}, 1, 2, 3)
and
[].concat({}, 1, 2, 3)
give the same result.
Given an instance arr of Array, arr.method is equivalent to Array.prototype.method.
You might read this as well: SO link