Sunday, September 18, 2016

Make a Copy of an Array in JavaScript

If you want to make a copy of an array in JavaScript, you can use Array#slice method. This way we will get a copy of the array. If we are simply assigning the array to another variable, it is not making a copy. So performing splice() operation on the array will affect the value stored in both variables.
var a = [1,2,3],
b = a;
a.splice(1,1); // => a is [1,3] and b is also [1,3]
var a = [1,2,3],
b = a.slice(0);
a.splice(1,1); // => a is [1,3] and b is [1,2,3]