JavaScript · The language round

What is the difference between a shallow and deep copy?

MediumobjectscopyingimmutabilityUpdated Oct 2026
Quiz this track

Short answer

A shallow copy duplicates the top level but shares nested objects. A deep copy recursively clones nested data. structuredClone() handles Dates, Maps, Sets and cycles better than JSON cloning.

Copying is about references. A shallow copy creates a new outer container, but nested objects still point to the same memory. A deep copy creates new nested containers too.

js
const original = { user: { name: "Asha" }, tags: ["js"] };
const shallow = { ...original };

shallow.user.name = "Ravi";
console.log(original.user.name); // "Ravi"

const deep = structuredClone(original);
deep.user.name = "Meera";
console.log(original.user.name); // "Ravi"
The spread copy shares user. structuredClone creates a separate nested object.

Ways to copy

  • Object spread or Object.assign({}, obj) for a shallow object copy
  • array.slice() or [...array] for a shallow array copy
  • structuredClone(value) for a deep copy of supported built-ins
  • A custom recursive function when you need class instances or special handling

JSON cloning is common but lossy. JSON.parse(JSON.stringify(value)) drops undefined, functions and symbols, turns Date into a string, throws on BigInt and cycles, and does not preserve prototypes.

js
const source = { when: new Date(), missing: undefined };
const jsonCopy = JSON.parse(JSON.stringify(source));

console.log(jsonCopy.when instanceof Date); // false
console.log("missing" in jsonCopy); // false
structuredClone cannot clone functions, DOM nodes or class prototypes. It does support cycles, which JSON cannot handle.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What are the limitations of JSON cloning?
  2. 2Does `structuredClone` preserve prototypes?
  3. 3How would you deep clone an object with functions?
  4. 4Why is immutability easier with shallow copies?

Say it in the interview

A shallow copy creates a new top-level object but nested objects are still shared. A deep copy recursively copies nested data. Spread and Object.assign are shallow. structuredClone is the modern deep-copy option and handles Dates, Maps, Sets and cycles. JSON cloning is lossy because it drops undefined and functions, turns dates into strings, and fails on BigInt or cycles.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.