Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JS array `concat` clarification

I understand how the concat method works, but I had one question about a line in the MDN docs.

It says:

The concat methods does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays.


My questions is, how is it possible for it to potentially alter the this? Is it saying that the argument arrays could potentially lose their this but instead it preserves it since it's simply creating a new array?

like image 230
qarthandso Avatar asked Jan 02 '23 22:01

qarthandso


1 Answers

In the call a.concat(b, c), the function being called is a.concat, the this value is a, and the arguments are b and c. What MDN is saying there is that the array a is not changed by that call – unlike, for example, a.push(x).

const arr = [1, 2, 3];

arr.concat([4, 5]);
console.log(arr.join(', '));
// the “this” array in the call `arr.concat([4, 5])` didn’t change

arr.push(6);
console.log(arr.join(', '));
// the “this” array in the call `arr.push(6)` changed
like image 52
Ry- Avatar answered Jan 04 '23 13:01

Ry-