CodeBlanks Logo Icon CodeBlanks

Copying with spread

JavaScript course · Advanced · Lesson 33/100

Learn to make shallow copies of arrays and objects with spread.

Shallow copy

Spread lets you take a shallow copy of an array or object. const copy = [...original] produces a new array; const copy = { ...original } produces a new object. Top-level values are independent; changing the copy does not affect the original.

This is ideal for immutable updates: you build a derived copy without touching the existing data. React and similar libraries rely on this pattern.

The nested caveat

Shallow copy only copies the first level. Nested objects or arrays are shared by reference. After const copy = { ...original }, writing copy.items.push(3) also changes original.items; both point to the same array.

When you need a deep copy, you use a method like structuredClone(original). Spread gives you a fast and readable shallow copy; that is enough most of the time.

Exercise Mutate the copy, not the original

Create an array called numbers (for example [1, 2, 3]). Use spread to make an independent copy called numbersCopy. Add a new item to the copy with numbersCopy.push(4). Then log both numbers and numbersCopy separately with console.log so you can see the original is unchanged.

Show example solution
const numbers = [1, 2, 3];
const numbersCopy = [...numbers];
numbersCopy.push(4);
console.log(numbers);
console.log(numbersCopy);

Test yourself

  1. What does shallow copy not copy?

    const original = { items: [1, 2] };
    const copy = { ...original };
    • Nested objects stay as references
    • All nested structures are deep-copied
    • Only the first property is copied
    • The original object is deleted
    Show answer

    Nested objects stay as references — Correct. Shallow copy only copies the top level; nested structures are shared.

  2. Shallow copy of an object

    const original = { theme: "light" };
    const copy = ____;
    console.log(copy);
    Show answer
    const original = { theme: "light" };
    const copy = {...original};
    console.log(copy);
  3. Match the copying concepts

    shallow copy
    Top-level copy, nested shared
    [...arr]
    Array copy
    {...obj}
    Object copy

All lessons in Advanced