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:
It’s common to see code for making a copy of an array by iterating over the elements:
After which we’re safe since we have an element-by-element copy of the original (safe if the elements are primitives!):
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:
And wouldn’t you know it - the second argument is optional:
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: