Copying array to a new variable in JavaScript

·

2 min read

In JavaScript array are reference values, i.e the variable point to a location in memory with the array data. For example:

let x = [1,2,3,4,5]

I have just defined a variable x to holds an array of length 5. I can then assign the value of x to a new variable y.

let y = x

I can then carry out an operation on y, in this case, I will perform the operation of pop on variable y. This special array function, removes the last element of the array.

y.pop() //this removes 5 which is the last element of the array.

Now if I perform var_dump on variable y, this is what I get:

var_dump(y) // returns [1,2,3,4]

If I perform var_dump on x, let's see what the result is:

var_dump(x) // return [1,2,3,4]

We can easily see that after an operation is done on only y, it takes effect on x as well and that is because x and y are just reference to a memory location hold the same array.

If you want y to have the same value of x, but be an independent array from x, this is how to go about it:

let y = x.slice()

With this any operation carried out on y, does not take effect on x as well.