Shallow cloning an array

suggest change

Sometimes, you need to work with an array while ensuring you don’t modify the original. Instead of a clone method, arrays have a slice method that lets you perform a shallow copy of any part of an array. Keep in mind that this only clones the first level. This works well with primitive types, like numbers and strings, but not objects.

To shallow-clone an array (i.e. have a new array instance but with the same elements), you can use the following one-liner:

const clone = arrayToClone.slice();

This calls the built-in JavaScript Array.prototype.slice method. If you pass arguments to slice, you can get more complicated behaviors that create shallow clones of only part of an array, but for our purposes just calling slice() will create a shallow copy of the entire array.

The same methods used to convert array-like objects to arrays also clone an array. In a non-strict script, assigning these names without a declaration creates globals.

const arrayToClone = [1, 2, 3, 4, 5];
const clone1 = Array.from(arrayToClone);
const clone2 = Array.of(...arrayToClone);
const clone3 = [...arrayToClone]; // the shortest way
const arrayToClone = [1, 2, 3, 4, 5];
const clone1 = Array.prototype.slice.call(arrayToClone);
const clone2 = [].slice.call(arrayToClone);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents