JavaScript · The language round
What is the difference between a shallow and deep copy?
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.
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"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 copystructuredClone(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.
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); // falsestructuredClone 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.
- 1What are the limitations of JSON cloning?
- 2Does `structuredClone` preserve prototypes?
- 3How would you deep clone an object with functions?
- 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.