CodeBlanks Logo Icon CodeBlanks

structuredClone

JavaScript course · Intermediate · Lesson 109/134

Learn to deep copy an object with structuredClone.

Deep copy of an object

If you copy an object with =, you only copy its reference; nested objects are shared. The structuredClone method produces a deep copy: every nested value is duplicated as a new object.

const original = { list: [1, 2] };
const copy = structuredClone(original);
copy.list.push(3);
// original.list is still [1, 2]

This lets you work on an independent copy without harming the original.

Circular references

If an object has a property that points back to itself, this is a circular reference. Copying with = keeps it, but classic deep-copy approaches can crash.

structuredClone handles circular references correctly; the structure is preserved.

const a = {};
a.self = a;
const copy = structuredClone(a);
// copy.self === copy

Exercise Make a deep copy

Make a deep copy of the template object and assign it to copy. Use the structuredClone method.

Show example solution
Call structuredClone with template.
Example solution:
const copy = structuredClone(template);

Test yourself

  1. What does structuredClone produce?

    structuredClone({a: {b: 1}})
    • A deep copy
    • A shallow copy
    • A reference
    • A string
    Show answer

    A deep copy — Correct! structuredClone makes a deep, independent copy.

  2. Change the copy, keep the original

    const copy = structuredClone(original);
    copy.list.____(3);
    Show answer
    const copy = structuredClone(original);
    copy.list.push(3);
  3. Copying an object with a circular reference

    const a = {}; a.self = a;
    • structuredClone throws
    • structuredClone copies correctly
    • Only = works
    • No method works
    Show answer

    structuredClone copies correctly — Correct! structuredClone supports circular references.

All lessons in Intermediate