Shallow copy of an array
What a "shallow copy" is
A shallow copy is a new array where:
- there is a new reference (changes in it do not affect the original);
- but nested objects are copied by reference.
1. With the spread operator (...) - the most modern way
javascript
const arr = [1, 2, 3];
const copy = [...arr];
console.log(copy); // [1, 2, 3]
console.log(copy === arr); // false (new array)This way makes a shallow copy - if the elements were objects, they still reference the same data:
javascript
const arr = [{ name: "Tim" }];
const copy = [...arr];
copy[0].name = "Alex";
console.log(arr[0].name); // "Alex" - because the object is shared2. With slice() and no arguments
javascript
const arr = [1, 2, 3];
const copy = arr.slice();
console.log(copy); // [1, 2, 3]slice()without parameters returns a new array - a copy of the whole original.- This is an old but reliable way.
3. With Array.from()
javascript
const arr = [1, 2, 3];
const copy = Array.from(arr);
console.log(copy); // [1, 2, 3]Useful if you want not just a copy, but, for example, to apply a transformation to each element:
javascript
const doubled = Array.from(arr, x => x * 2); // [2, 4, 6]4. With concat()
javascript
const arr = [1, 2, 3];
const copy = [].concat(arr);
console.log(copy); // [1, 2, 3]This works because concat() returns a new array
and does not modify the original.
What is not copied deeply
All the listed methods copy only the top level. If the array has objects or nested arrays, they stay by reference.
javascript
const arr = [[1, 2], [3, 4]];
const copy = [...arr];
copy[0][0] = 99;
console.log(arr[0][0]); // 99 - because the nested array is sharedIn short:
| Way | Code | Creates a new array | Deep copy? |
|---|---|---|---|
| Spread | [...arr] | Yes | No |
slice() | arr.slice() | Yes | No |
Array.from() | Array.from(arr) | Yes | No |
concat() | [].concat(arr) | Yes | No |
Summary: To make a shallow copy of an array, use:
javascriptconst copy = [...arr];And if you need deep copying (together with nested objects) - you can use
structuredClone(arr)orJSON.parse(JSON.stringify(arr)).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.