JavaScript.push () internal function overrides a global variable

I have the following problem with the .push() method:

 var myArray = ["a", "b", "c", "d"]; function add(arr) { arr.push("e"); return arr; } add(myArray); // myArray is now ["a", "b", "c", "d", "e"] 

Why does it override myArray ? I can’t understand what ...

+4
source share
2 answers

Arrays in Javascript (and most other languages) are passed by reference.

When you write add(myArray) , you pass a reference to the same instance of the array to which the global variable myArray belongs.
Any changes to the array object will be visible through both links.

To copy the actual array instance, write add(myArray.slice()); .
Please note that this will not copy objects inside it.

+9
source

If you need to be able to embed arrays, I would .add() function so that .concat() duplicates Array in the variable, .push() new value in the new array and returns it.

 function add(arr) { var newArr = arr.concat(); // duplicate newArr.push("e"); // push new value return newArr; // return new (modified) Array } 

You can also use concat() and return the new array that it creates.

 var myArray = ["a", "b", "c", "d"]; function add(arr) { return arr.concat("e"); } var newArray = add(myArray); console.log( newArray ); // ["a", "b", "c", "d", "e"] console.log( myArray ); // ["a", "b", "c", "d"] 

So, instead of the two methods .slice() , then .push() , you will execute it with one .concat() .

This also gives the advantage of passing another array instead of a string, therefore:

 return arr.concat(["e","f"]); 

will provide you with:

 // ["a", "b", "c", "d", "e", "f"] 

instead:

 // ["a", "b", "c", "d", ["e", "f"] ] 
+4
source

All Articles