Copying Arrays in Javascript

Javascript Code Snippets Copying An Array
Share:

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);

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger