Copying A Javascript Array

2020-02-17

Javascript Arrays are Objects, Objects are passed by reference every change in the original object effects all copies and vice versa.

var original = [1, 2, 3, 4, 5];
var copy = original;

original.push(6);
console.log(original); // [ 1, 2, 3, 4, 5, 6 ]
console.log(copy);     // [ 1, 2, 3, 4, 5, 6 ]

This type of copy is known as a Shalow Copy, if an array needs to be totaly copied without references a Deep Copy is required:

var original = [1, 2, 3, 4, 5];
var copy = [];

for(var i = 0; i < original.length; i++) {
    copy[i] = original[i];
}

original.push(6);
console.log(copy); // [ 1, 2, 3, 4, 5 ]

Other Ways To Deep Copy

Using concat()

var original = [1, 2, 3, 4, 5];
var copy = original.concat([]);

original.push(6);
console.log(original); // 1,2,3,4,5,6
console.log(copy);     // 1,2,3,4,5

Using slice()

var original = [1, 2, 3, 4, 5];
var copy = original.slice(0);

original.push(6);
console.log(original); // 1,2,3,4,5,6
console.log(copy);     // 1,2,3,4,5

Using splice() (mutates the original)

var original = [1, 2, 3, 4, 5];
var copy = original.splice(0);

original.push(6);
console.log(original); // 6
console.log(copy);     // 1,2,3,4,5

cy6erlion