Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 4 · Lesson 39 · 5 min read

JavaScript Deep Copy vs Shallow Copy: structuredClone

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Updating Nested Cart State Immutably
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Distinguish values from references, predict when mutations are shared, make shallow and deep copies correctly with spread, structuredClone and the newer non-mutating array methods, write immutable updates for nested state, and understand why frameworks rely on reference equality.

Concept Explanation

Primitives are stored and compared by value: two strings with the same characters are equal. Objects, including arrays and functions, are stored and compared by reference: a variable holds a pointer to the object, and two variables can point to the same object. Assigning an object to another variable, passing it to a function or storing it in an array does not copy it. Changing it through any of those references changes the one shared object. That is efficient, but it is also the source of many bugs where one part of an application unexpectedly sees another part's changes.

Equality follows the same rule. Two different objects with identical contents are not equal with ===, while two references to the same object are. Frameworks exploit this: React, and most state libraries, decide whether something changed by comparing references with Object.is. If you mutate an object in place and pass the same reference back, the framework sees no change and does not re-render. If you create a new object for every change, a single reference comparison detects it, which is far cheaper than comparing contents deeply.

Copying comes in two depths. A shallow copy creates a new outer object but shares everything nested inside. Spread syntax, {...obj} and [...arr], Object.assign and Array.prototype.slice all make shallow copies. That is usually what you want for immutable updates, because unchanged nested data can be shared safely. A deep copy duplicates every level. structuredClone, available in browsers and Node, deep copies objects, arrays, maps, sets, dates, typed arrays and even circular references. It cannot clone functions, DOM nodes or class instances' prototypes. The old trick JSON.parse(JSON.stringify(x)) loses dates, undefined, maps and sets and fails on cycles, so prefer structuredClone.

Immutable updates follow a simple recipe: copy each level along the path to the change, and reuse everything else. To change one item's quantity inside a cart inside state, you copy state, copy the items array and copy the one item, while every other item keeps its reference. Array methods help: map, filter and concat already return new arrays, and ECMAScript 2023 added toSorted, toReversed, toSpliced and with as non-mutating versions of sort, reverse, splice and index assignment. Sorting with the old sort mutates the array in place, a classic bug when the array is component state.

For deeply nested updates, libraries such as Immer let you write code that looks like mutation against a draft and produce a correct immutable result, which is what Redux Toolkit uses internally. Object.freeze prevents changes to an object's own properties, but it is shallow and is mainly useful in development to catch accidental mutation.

OperationMutatesDepthNote
Assignment b = aShares the objectNoneSame reference
Spread {...a}, [...a]NoShallowNested objects shared
structuredClone(a)NoDeepMaps, sets, dates, cycles; no functions
JSON round tripNoDeepLoses dates, undefined, maps; fails on cycles
sort, reverse, spliceYesIn placeAvoid on state
toSorted, toReversed, toSpliced, withNoShallow copyES2023 non-mutating versions
Object.freezePrevents changesShallowUseful in development

Worked Example: Updating Nested Cart State Immutably

The buggy update mutates state in place, so a reference comparison sees no change. The fixed version copies only the path to the change.

JavaScript
const state = {
  user: { id: 7, name: 'Ana' },
  cart: {
    items: [
      { sku: 'A1', qty: 1, price: 1200 },
      { sku: 'B2', qty: 2, price: 450 },
    ],
  },
};

// Buggy: mutation keeps every reference the same
function setQtyBad(s, sku, qty) {
  s.cart.items.find((i) => i.sku === sku).qty = qty;
  return s;
}
const bad = setQtyBad(state, 'B2', 3);
console.log(bad === state);                  // true: a framework would not re-render

// Correct: copy the path, share the rest
function setQty(s, sku, qty) {
  return {
    ...s,
    cart: {
      ...s.cart,
      items: s.cart.items.map((i) => (i.sku === sku ? { ...i, qty } : i)),
    },
  };
}
const next = setQty(state, 'A1', 4);
console.log(next === state);                         // false: change detected
console.log(next.user === state.user);               // true: untouched branch is shared
console.log(next.cart.items[1] === state.cart.items[1]);   // true: unchanged item shared

// Non-mutating array methods
const byPrice = next.cart.items.toSorted((a, b) => a.price - b.price);   // original order intact
const withoutFirst = next.cart.items.toSpliced(0, 1);
const replaced = next.cart.items.with(0, { sku: 'C3', qty: 1, price: 999 });

// Deep copy for a draft the user may discard
const draft = structuredClone(next);
draft.cart.items[0].qty = 99;
console.log(next.cart.items[0].qty);                 // 4: the original is unaffected

Sharing untouched branches is not a shortcut; it is the point. Components that receive state.user can skip re-rendering because their input reference did not change.

To change one cart item immutably, copy the state object, the cart, the items array and the changed item. The user object and every other item keep their references, so a reference comparison finds exactly what changed.
To change one cart item immutably, copy the state object, the cart, the items array and the changed item. The user object and every other item keep their references, so a reference comparison finds exactly what changed.

Real-World Examples

  • Redux's documentation requires reducers to update state immutably and explains that its connected components and selectors detect changes by reference, and Redux Toolkit adopted Immer so developers could write mutating-style code in reducers safely.
  • The change array by copy proposal, which added toSorted, toReversed, toSpliced and with in ECMAScript 2023, cited the frequency of accidental in-place sort bugs and the cost of copying arrays before sorting as motivation.
Key TakeawaysJavaScript objects are shared by reference, so assigning or passing an object never copies it, and the === operator compares identity, not contents. Frameworks detect change by reference, so update state immutably: copy each level along the path to a change and share the rest. Use spread for shallow copies, structuredClone for deep ones, the ES2023 non-mutating array methods instead of sort, reverse and splice, and Immer for deep updates.

Review Questions & Answers

Frameworks compare the previous and next state by reference. Mutating the existing object leaves the reference unchanged, so the comparison reports no change and the update is skipped or rendered inconsistently.

A shallow copy creates a new top-level object or array but shares all nested objects with the original. A deep copy duplicates every nested level, so no objects are shared and changes to the copy never affect the original.

structuredClone preserves dates, maps, sets, typed arrays, undefined values and circular references. The JSON round trip turns dates into strings, drops undefined and functions, turns maps and sets into empty objects and throws on circular references.

sort mutates the array in place, changing the state without changing its reference and affecting every other place that holds the array. toSorted returns a new sorted array and leaves the original untouched.