Skip to main content

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 shared

2. 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 shared

In short:

WayCodeCreates a new arrayDeep copy?
Spread[...arr]YesNo
slice()arr.slice()YesNo
Array.from()Array.from(arr)YesNo
concat()[].concat(arr)YesNo

Summary: To make a shallow copy of an array, use:

javascript
const copy = [...arr];

And if you need deep copying (together with nested objects) - you can use structuredClone(arr) or JSON.parse(JSON.stringify(arr)).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.