I have the following problem with .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 it overrides myArray? Can’t understand that…
Arrays in Javascript (and most other languages) are passed by reference.
When you write
add(myArray), you are passing a reference to the same Array instance that the globalmyArrayvariable refers to.Any changes to the array object will be visible through both references.
To copy the actual array instance, write
add(myArray.slice());.Note that this will not copy the objects inside of it.