Copying an Array in JavaScript
Of course when you assign an existing object to a variable in JavaScript, you actually receive a reference to the object. So modifications on the reference, cause changes on the original. This shouldn’t be a surprise at all, and just to illustrate:
var a = [1, 2, 3];
var b = a;
b.push(4);
a; // [1, 2, 3, 4]
It’s common to see code for making a copy of an array by iterating over the elements:
var a = [1, 2, 3];
var b = new Array(a.length);
for (var i = 0; i < a.length; i++) {
b[i] = a[i];
}
After which we’re safe since we have an element-by-element copy of the original (safe if the elements are primitives!):
b.push(4);
a; // [1, 2, 3]
Pretty ugly code for such a simple, common operation. Luckily JavaScript has a nifty method on Array called “slice”, which is for selecting a segment of an existing Array. We can abuse slice to make the copy for us:
var a = [1, 2, 3];
var b = a.slice(0, a.length);
b.push(4);
a; // [1, 2, 3]
And wouldn’t you know it - the second argument is optional:
var a = [1, 2, 3];
var b = a.slice(0);
AND, don’t tell the old-school JavaScript developers but if you’re programming in a decently new version of JavaScript (hey node.js guys) - that first argument is also optional:
var a = [1, 2, 3];
var b = a.slice();