About
In this code snippet, we’ll learn how to copy an array in Javascript.
In Javascript, if you assign an array to another array using the = assignment operator you won’t actually copy the values from one array into the other. What you will do is make another reference to the first array, so now you just have to variables pointing at the same array.
To copy the actual array you need to do this arrayCopy = […originalArray ].
Let’s see the example below.
Code:
//Make array. array = [1, 2, 3]; //Copy the array.(well not really) arrayCopy = array; //Add an element. arrayCopy.push(4); //Print the arrays. //We would expect the contents of the first array to be 1 2 3 and contents of the second array to be 1 2 3 4. console.log(array); console.log(arrayCopy); //Reset array to original values. array = [1, 2, 3]; //Now we are actualy copying the array and not just the reference. arrayCopy = [...array]; //Add element. arrayCopy.push(4); //Now we will get the expected output. console.log(array); console.log(arrayCopy);