Reputation: 2549
I'm trying to concat two arrays in javascript using concat()
method. I'm wondering what is the difference between these two cases
var a = [1, 2, 3];
console.log(Array.prototype.concat.call(a, [4, 5, 6]));
// Result: [1, 2, 3, 4, 5, 6]
console.log(Array.prototype.concat(a, [4, 5, 6]));
// Result: [1, 2, 3, 4, 5, 6]
I thought by using call
method, as we are passing in this
object as the first argument, it would change the array a
. But it didn't.
Upvotes: 0
Views: 765
Reputation: 664599
Array.prototype.concat.call(a, [4, 5, 6])
is equivalent to a.concat([4, 5, 6])
(assuming a.concat === Array.prototype.concat
, which is the case in your example where a instanceof Array
).
Array.prototype.concat(a, [4, 5, 6])
is equivalent to Array.prototype.concat.call(Array.prototype, a, [4, 5, 6])
.
Given that Array.prototype
is an empty array, both yield the same result. [].concat(a, [4, 5, 6])
or Array.prototype.concat.call([], a, [4, 5, 6])
would as well.
Upvotes: 2
Reputation: 687
Array.prototype.concat
returns a new array. So Array.prototype.concat(a, [4, 5, 6])
and Array.prototype.concat.call(a, [4, 5, 6])
actually do the same thing. If you want to change the original array, you should, use Array.prototype.push.apply(a, [4, 5, 6])
Upvotes: 2