QJavaScript · Interview preparation
What is the difference between shallow and deep copies?
A shallow copy duplicates only the outer container, leaving nested references shared.
The idea to remember.
A shallow copy duplicates only the outer container, leaving nested references shared. A deep copy recursively separates supported nested values; structuredClone helps with many built-in types but not every object.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: understand this
01 / BEGINNERThe call site determines this for ordinary functions.
const account = {
balance: 10,
show() { return this.balance; }
};
console.log(account.show()); // 10Intermediate: copy before changes
02 / INTERMEDIATESpread makes a shallow copy; nested objects still share references.
const user = { name: 'Ava', settings: { dark: false } };
const updated = { ...user, settings: { ...user.settings, dark: true } };Real scenario: normalize API data
03 / REAL SCENARIOMake defaults explicit at an untrusted API boundary.
function normalizeUser(data) {
return {
id: String(data.id),
name: typeof data.name === 'string' ? data.name : 'Guest'
};
}02Check your understanding
Try it in your own words.
Explain what is the difference between shallow and deep copies without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse JavaScript study guides ↗