Tech Interview RoomStudy guides

JavaScript

Explain shallow copy vs deep copy. How do you clone an object correctly?

Intermediate · 2 min read · Lesson 9 of 12 in JavaScript

  • A shallow copy creates a new top-level object, but nested objects are still shared by reference.
  • A deep copy recursively copies every nested object, so the copy is fully independent.

Options

  • Spread {...obj}, [...arr], Object.assign and Array.from: shallow.
  • JSON.parse(JSON.stringify(obj)): deep, but loses undefined, functions, Symbols, Date (becomes a string), Map, Set, RegExp, and throws on circular references and BigInt.
  • structuredClone(obj): built-in deep copy. Handles Date, Map, Set, typed arrays, RegExp and circular references. It cannot clone functions, DOM nodes or class prototypes (instances become plain objects).

Why it matters in frontend code

React and Vue state updates rely on immutability: change a nested field by copying the path you change ({...state, user: {...state.user, name}}) instead of deep-cloning everything, which is slow and breaks memoisation for unchanged branches.

Example

js
const original = { name: 'A', tags: ['x'], created: new Date(0) };

const shallow = { ...original };
shallow.tags.push('y');
console.log(original.tags);              // [ 'x', 'y' ]: shared!

const deep = structuredClone(original);
deep.tags.push('z');
console.log(original.tags.length, deep.tags.length); // 2 3
console.log(deep.created instanceof Date);           // true

const viaJson = JSON.parse(JSON.stringify(original));
console.log(typeof viaJson.created);                 // string

Follow-up questions interviewers ask

Try answering each one before you open it.

How would you write a deep clone by hand?

Recurse over own keys, return primitives and functions as they are, create [] or {} per level, and keep a WeakMap from originals to copies so circular references and shared objects are copied once. Handle Date, Map and Set explicitly. The Frontend Coding topic has a runnable version.