Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 156 Β· Objects

Copying Objects: Shallow and Deep

Understand object references in JavaScript, make shallow copies with spread and Object.assign, deep copies with structuredClone, and compare objects correctly.

Here's a bug almost every JavaScript developer writes at least once: you "copy" an object, change the copy, and the original changes too. It happens because variables don't hold objects. They hold references to objects, and assigning a reference just gives you a second way to reach the same thing.

This lesson explains how references work, then shows the three levels of copying: no copy at all (sharing), a shallow copy (a new outer object whose nested values are still shared) and a deep copy (fully independent at every level). You'll also learn how to compare objects, since === checks references, not contents.

Values and references

Primitives such as numbers, strings and booleans are copied by value. Each variable gets its own independent value:

JavaScript
let a = 10;
let b = a;   // b gets its own 10
b = 99;
console.log(a); // 10

Objects, arrays and functions work differently. The variable holds a reference, a pointer to where the object lives in memory. Copying the variable copies the pointer:

JS Two names, one object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There's only one object here, reachable through two names. Changing it through either name changes "both", because there is no "both".

Note the last example: reassigning a variable just points it somewhere else. Only mutating (changing a property, pushing to an array) affects the shared object. This is also why const doesn't make objects unchangeable: const stops reassignment of the variable, not mutation of the object, as you saw in Variables.

Shallow copies

A shallow copy creates a new outer object and copies each top-level property into it. JavaScript gives you several ways to do it:

JavaScript
const objCopy1 = { ...source };                 // object spread
const objCopy2 = Object.assign({}, source);     // Object.assign

const arrCopy1 = [...list];                     // array spread
const arrCopy2 = list.slice();                  // slice with no arguments
const arrCopy3 = Array.from(list);              // Array.from

For flat data, where every property is a primitive, a shallow copy is all you need. The trouble starts with nested objects. Each property is copied the way a variable is copied, so a nested object's reference is copied, not the nested object:

JS Where shallow copies leak

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The outer objects are different, but copy.skills and profile.skills are the same array. Think of a shallow copy as a new folder that holds shortcuts to the same subfolders.

Copying just the levels you change

Often you don't need a full deep copy. You just need to copy the path you're about to change. Spread each level along that path:

JavaScript
const updated = {
  ...profile,
  address: { ...profile.address, city: "Alexandria" },
};
// profile.address is untouched; skills is still shared (and that's fine
// as long as nobody mutates it)

This is the standard pattern in code that treats data as immutable, such as React or Redux state. It is fast, because unchanged parts are shared rather than copied.

Deep copies with structuredClone()

A deep copy duplicates everything: the object, every nested object and array, all the way down. The modern built-in for this is structuredClone():

JS structuredClone()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

structuredClone() is available in all modern browsers (since 2022), Node.js 17+ and Deno. It handles plain objects, arrays, Date, Map, Set, RegExp, typed arrays, Blob, errors and circular references.

It has limits, though:

  • Functions can't be cloned. An object with a method throws a DataCloneError.
  • DOM nodes can't be cloned (use node.cloneNode(true) for those).
  • Class instances lose their class. You get a plain object with the same data, but no prototype methods.
  • Getters are run and their current values are copied, just like with spread.
JS What structuredClone can't do

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For class instances, the usual answer is to give the class its own clone() method that creates a new instance, for example return new Point(this.x, this.y);.

The old JSON trick

Before structuredClone(), people deep-copied with JSON.parse(JSON.stringify(obj)). It still appears in older code. It works for plain data, but as you saw in JSON, it turns dates into strings, drops undefined and functions, empties Maps and Sets, turns NaN into null and throws on circular references. Prefer structuredClone().

Choosing a strategy

You need… Use
A second name for the same object Plain assignment (no copy)
An independent copy of flat data { ...obj } or [...arr]
To change one nested value without mutating Spread each level along the path
A fully independent copy of plain data structuredClone(obj)
A copy of a class instance A clone() method on the class

Deep copying everything "to be safe" is wasteful for large data, and it breaks the cheap reference checks that many UI libraries rely on. Copy as much as you need, not more.

Comparing objects

Since variables hold references, === (and ==) compares identity, not contents. Two separate objects are never equal, even with identical properties:

JS Equality checks identity

Press Run (or Ctrl + Enter) to see the console output here.

No output.

To compare contents, you have to look inside. A shallow comparison checks each top-level property with === or Object.is() (see Comparison and Equality). A deep comparison recurses into nested objects; it's a good exercise once you've read Recursion, and libraries such as Lodash ship a tested isEqual().

Comparing JSON.stringify(a) === JSON.stringify(b) is a quick hack for simple data, but it fails when key order differs ({x:1, y:2} vs {y:2, x:1}) and inherits all of JSON's type losses.

Preventing changes with Object.freeze()

If you want to guarantee nobody mutates an object, Object.freeze() makes its properties read-only. Like spread, it is shallow: nested objects stay changeable unless you freeze them too.

JavaScript
const config = Object.freeze({ mode: "prod", limits: { users: 100 } });
config.mode = "dev";        // ignored (throws in strict mode)
config.limits.users = 999;  // works! limits is not frozen

You met freeze in Working with Objects. It's useful for constants and shared configuration, but most code simply follows the convention of not mutating data it doesn't own.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. After const b = a; b.count = 5;, what is a.count?

    Assigning an object to a new variable copies the reference, not the object. Both names reach the same object.
  2. 2. const copy = [...matrix]; where matrix is an array of arrays. Then copy[0].push(9). What happens to matrix[0]?

    Array spread is shallow. The outer array is new, but copy[0] and matrix[0] are the same inner array.
  3. 3. Which value can structuredClone() NOT copy?

    Functions can't be cloned, so it throws a DataCloneError. Maps, Dates and circular references are all supported.
  4. 4. What does ({ id: 1 }) === ({ id: 1 }) evaluate to?

    === compares object identity. These are two separate objects, so they are not equal even though their contents match.
  5. 5. You need to change state.user.name without mutating state. Which is the lightest correct approach?

    Copy each level along the path you change. The third option still mutates the shared user object.

Summary

  • Variables hold references to objects; assigning or passing an object never copies it.
  • Mutating through one reference is visible through all of them; reassigning a variable is not.
  • Shallow copies ({ ...obj }, Object.assign(), [...arr], slice()) duplicate only the top level; nested values stay shared.
  • To update nested data immutably, spread each level along the path you change.
  • structuredClone() makes deep copies, keeps Dates, Maps and Sets, and handles cycles, but can't clone functions, DOM nodes or class prototypes.
  • === compares identity; compare contents with a shallow or deep equality function.

Next: Property Descriptors and Object Protection.