In the Spread & Rest Operators chapter we copied arrays and objects with [...arr] and { ...obj }, and we saw a warning more than once: "this is a shallow copy".
What does "shallow" mean, and why should you care? Look at this:
const student = {
name: "Aman",
marks: [80, 90],
address: { city: "Delhi" }
};
const copy = { ...student }; // shallow copy
copy.name = "Priya"; // top level: independent
copy.address.city = "Mumbai"; // nested: SHARED!
copy.marks.push(100); // nested: SHARED!
console.log(student.name);
console.log(student.address.city);
console.log(student.marks);
console.log(copy === student);
console.log(copy.address === student.address);Output:
Aman
Mumbai
[ 80, 90, 100 ]
false
trueWe changed the copy, but the original student's city and marks changed too. Bugs like this are very common, especially in React and other frontend code. In this chapter, we'll understand exactly why it happens and how to make a true, independent copy.
Shallow Copy vs Deep Copy in One Line
A shallow copy creates a new outer object, but nested objects and arrays inside it are still shared with the original. A deep copy creates new copies of everything, at every level, so nothing is shared.
Think of photocopying a project file. A shallow copy is like copying only the cover page and putting the same original pages behind it: write on page 3 of the "copy" and the original's page 3 changes too. A deep copy photocopies every single page.
First: Values vs References
To understand copying, we need one key idea about how JavaScript stores data.
Primitives (
number,string,boolean,null,undefined,bigint,symbol) are copied by value. The variable holds the value itself.Objects (including arrays and functions) are accessed by reference. The variable holds a reference, like an address telling JavaScript where the object lives in memory.
// Primitives: the value itself is copied
let a = 10;
let b = a;
b = 20;
console.log(a, b);
// Objects: only the reference is copied
const original = { name: "Aman", marks: 80 };
const sameObject = original;
sameObject.marks = 95;
console.log(original.marks);
console.log(original === sameObject);Output:
10 20
95
truea ──► 10 original ──┐
b ──► 20 sameObject ──┴──► { name: "Aman", marks: 95 }
Two separate numbers. Two variables, ONE object.So const sameObject = original is not a copy at all. It's just a second name for the same object. And === on objects checks whether two references point to the same object, not whether they look the same.
Shallow Copy
A shallow copy creates a new top-level object or array and copies each property into it. But if a property's value is itself an object or array, only its reference is copied.
Here's what happened in the opening example:
student ──► { name: "Aman", marks: ─┐, address: ─┐ }
│ │
▼ ▼
[80, 90] { city: "Delhi" }
▲ ▲
│ │
copy ──► { name: "Aman", marks: ─┘, address: ─┘ }Two different outer objects, but they point to the same marks array and the same address object. Changing copy.name is safe (it's a primitive stored in the new object). Changing copy.address.city changes the shared object.
Ways to Make a Shallow Copy
const nums = [1, 2, 3];
const user = { name: "Ravi", age: 21 };
const a1 = [...nums];
const a2 = nums.slice();
const a3 = Array.from(nums);
const a4 = [].concat(nums);
const o1 = { ...user };
const o2 = Object.assign({}, user);
console.log(a1, a2, a3, a4);
console.log(o1, o2);
console.log(a1 === nums, o1 === user);Output:
[ 1, 2, 3 ] [ 1, 2, 3 ] [ 1, 2, 3 ] [ 1, 2, 3 ]
{ name: 'Ravi', age: 21 } { name: 'Ravi', age: 21 }
false falseAll of these are shallow. Array methods like map() and filter() also return new arrays, but the objects inside are the same objects as before.
The Same Problem with Arrays
A 2D array (an array of arrays) is a classic trap, for example when copying a game board or a DP table:
const matrix = [[1, 2], [3, 4]];
const copy = [...matrix];
copy[0][0] = 99;
copy.push([5, 6]);
console.log(matrix);
console.log(copy);Output:
[ [ 99, 2 ], [ 3, 4 ] ]
[ [ 99, 2 ], [ 3, 4 ], [ 5, 6 ] ]push() only changed the copy (the outer arrays are different), but copy[0][0] = 99 changed a row that both share.
Replacing vs Mutating
Sharing only causes problems when you change the inside of a nested object. If you replace the whole nested value, the original is safe:
const original = { tags: ["js"] };
const copy = { ...original };
copy.tags = ["python"]; // replacing, not mutating
console.log(original.tags);
const copy2 = { ...original };
copy2.tags.push("react"); // mutating the shared array
console.log(original.tags);Output:
[ 'js' ]
[ 'js', 'react' ]Replacing makes copy.tags point to a new array. Mutating (push, setting a property) changes the array that both objects point to.
Deep Copy
A deep copy copies the object, then every object inside it, then every object inside those, all the way down. The result shares nothing with the original.
Method 1: structuredClone() (Recommended)
Modern JavaScript has a built-in function for deep copying: structuredClone(). It's available in all modern browsers (since 2022) and Node.js 17+.
const student = {
name: "Aman",
marks: [80, 90],
address: { city: "Delhi" }
};
const deep = structuredClone(student);
deep.address.city = "Mumbai";
deep.marks.push(100);
console.log(student.address.city);
console.log(student.marks);
console.log(deep.address.city);
console.log(deep.marks);
console.log(deep.address === student.address);Output:
Delhi
[ 80, 90 ]
Mumbai
[ 80, 90, 100 ]
falseThe original is completely untouched. structuredClone() also correctly handles many built-in types and even circular references (an object that points to itself):
const event = {
title: "Placement Drive",
date: new Date("2026-12-01T10:00:00Z"),
rooms: new Set(["A101", "B202"]),
budget: undefined
};
event.self = event; // circular reference: the object points to itself
const clone = structuredClone(event);
console.log(clone.date instanceof Date);
console.log(clone.date.toISOString());
console.log(clone.rooms.has("A101"));
console.log("budget" in clone);
console.log(clone.self === clone);
console.log(clone.self === event);Output:
true
2026-12-01T10:00:00.000Z
true
true
true
falseThe Date (covered in the Date & Time chapter) stays a real Date, the Set (covered in the next chapter) stays a Set, the undefined property is kept, and the cloned self points to the clone, not back to the original.
What structuredClone() Can't Do
1. It can't copy functions. An object containing a function (including methods) throws an error:
const withFunction = {
name: "Calculator",
add: (x, y) => x + y
};
structuredClone(withFunction);Output (Node.js; browsers show a similar DataCloneError):
DOMException [DataCloneError]: (x, y) => x + y could not be cloned.2. Class instances become plain objects. The data is copied, but the link to the class's prototype is lost, so methods disappear:
class Student {
constructor(name) {
this.name = name;
}
greet() {
return "Hi, " + this.name;
}
}
const s = new Student("Kiran");
const c = structuredClone(s);
console.log(c.name);
console.log(c instanceof Student);
console.log(typeof c.greet);Output:
Kiran
false
undefined3. Some details are dropped: getters and setters become plain values, frozen objects are not frozen in the copy, and properties with symbol keys are skipped. DOM elements can't be cloned at all.
Method 2: JSON.parse(JSON.stringify()) (The Old Trick)
Before structuredClone() existed, the common trick was to turn the object into a JSON string and then parse it back into a brand new object. (We'll study JSON properly in the JSON chapter.)
const original = { a: { b: 1 } };
const copy = JSON.parse(JSON.stringify(original));
copy.a.b = 2;
console.log(original.a.b, copy.a.b);Output:
1 2It works for simple data, but it silently loses or changes many values, because JSON only understands strings, numbers, booleans, null, arrays and plain objects:
const original = {
name: "Aman",
joined: new Date("2026-01-15T00:00:00Z"),
nickname: undefined,
sayHi() { return "Hi"; },
score: NaN,
skills: new Set(["JS"])
};
const copy = JSON.parse(JSON.stringify(original));
console.log(copy);
console.log(typeof copy.joined);Output:
{
name: 'Aman',
joined: '2026-01-15T00:00:00.000Z',
score: null,
skills: {}
}
stringLook at the damage:
The
Datebecame a string.nickname(undefined) andsayHi(a function) disappeared.NaNbecamenull(the same happens toInfinity).The
Setbecame an empty object.
It also throws for circular references (TypeError: Converting circular structure to JSON) and for BigInt values. Use it only when you know the data is plain JSON-like data, and prefer structuredClone() otherwise.
Method 3: Write Your Own Recursive Deep Clone
"Implement deep clone" is a very popular interview question. The idea is recursion: copy primitives directly, and for objects and arrays, create a new container and deep clone each value inside it.
function deepClone(value) {
// 1. Primitives (and null) are copied by value already
if (value === null || typeof value !== "object") {
return value;
}
// 2. Arrays: clone every element
if (Array.isArray(value)) {
return value.map(item => deepClone(item));
}
// 3. Plain objects: clone every own property
const result = {};
for (const key of Object.keys(value)) {
result[key] = deepClone(value[key]);
}
return result;
}
const college = {
name: "ABC Institute",
departments: [
{ code: "CSE", seats: 120 },
{ code: "ECE", seats: 60 }
],
address: { city: "Hyderabad", pin: 500001 }
};
const copy = deepClone(college);
copy.departments[0].seats = 180;
copy.address.city = "Bengaluru";
console.log(college.departments[0].seats);
console.log(college.address.city);
console.log(copy.departments[0].seats);
console.log(copy.address.city);Output:
120
Hyderabad
180
BengaluruNote: typeof null is "object", which is why we check value === null first. Functions have typeof "function", so this version simply copies their reference (which is usually fine, since functions are rarely modified).
Handling Circular References
The simple version above runs forever (until a "Maximum call stack size exceeded" error) on an object that points to itself. The fix: remember every object we've already cloned. If we meet it again, return the clone we already made. Here we use a Map (explained in the next chapter) as a lookup table from "original object" to "its clone":
function deepClone(value, seen = new Map()) {
if (value === null || typeof value !== "object") {
return value;
}
// Already cloned this object? Return that clone (handles cycles)
if (seen.has(value)) {
return seen.get(value);
}
const result = Array.isArray(value) ? [] : {};
seen.set(value, result); // remember BEFORE cloning children
for (const key of Object.keys(value)) {
result[key] = deepClone(value[key], seen);
}
return result;
}
const node = { value: 1 };
node.next = node; // points to itself
const copy = deepClone(node);
console.log(copy.value);
console.log(copy.next === copy);
console.log(copy.next === node);
const shared = { x: 1 };
const pair = { left: shared, right: shared };
const pairCopy = deepClone(pair);
console.log(pairCopy.left === pairCopy.right);
console.log(pairCopy.left === shared);Output:
1
true
false
true
falseThe seen map also keeps shared references shared: left and right pointed to the same object before, and in the copy they point to the same (new) object too. This version still doesn't handle special types like Date, Map or class instances, which is exactly why structuredClone() or a library function like Lodash's _.cloneDeep() is used in real projects.
Time and Space Complexity
Operation | Time | Extra space |
|---|---|---|
Assignment ( | O(1) | O(1), nothing is copied |
Shallow copy | O(k), where k = number of top-level properties/elements | O(k) |
Deep copy | O(N), where N = total number of values at all levels | O(N) for the copy, plus O(d) recursion stack for depth d |
For example, an array of 1,000 student objects with 5 fields each: a shallow copy copies 1,000 references, while a deep copy creates 1,000 new objects and copies 5,000 field values. Deep copying is more expensive, so only do it when you really need independence at every level.
Updating Nested Data Without Deep Copying Everything
In React and similar libraries, you must not mutate state; you create a new version instead. Deep cloning the whole state every time is wasteful. The common pattern is to shallow copy only along the path you change:
const state = {
user: { name: "Aman", address: { city: "Delhi", pin: 110001 } },
theme: "dark"
};
// Update only the city, without touching the original
const newState = {
...state,
user: {
...state.user,
address: {
...state.user.address,
city: "Pune"
}
}
};
console.log(state.user.address.city);
console.log(newState.user.address.city);
console.log(newState.theme);
console.log(newState.user.address === state.user.address);Output:
Delhi
Pune
dark
falseEvery object on the path to city is new, and everything else (like theme, or any untouched branch) is reused safely. The original state is unchanged.
All Methods Compared
Method | Depth | Functions | Date / Map / Set | Circular refs |
|---|---|---|---|---|
| No copy at all | - | - | - |
| Shallow | Reference copied | Reference copied | No problem (nothing nested is copied) |
| Shallow | Reference copied | Reference copied | No problem |
| Deep | Dropped | Date → string, Map/Set → | Throws |
| Deep | Throws | Kept correctly | Handled |
Custom recursive function | Deep | Whatever you decide | Only if you handle them | Only with a |
Common Mistakes
Thinking
=copies an object. It only copies the reference. Both variables point to the same object.Thinking spread is a deep copy.
{ ...obj }and[...arr]copy only one level.Copying a 2D array with
[...grid]. The rows are still shared. Usegrid.map(row => [...row])orstructuredClone(grid).Using the JSON trick on data with dates,
undefined, functions,Map/SetorNaN. These are silently changed or lost.Calling
structuredClone()on objects with methods or class instances. Functions throw an error, and class instances lose their methods.Expecting
Object.freeze()to be deep. Like copying, freezing only affects the top level (see the Object Methods chapter).Comparing copies with
===. Two separate objects are never===, even if they contain the same data.
Interview Tips
A good short answer to "What's the difference between a shallow copy and a deep copy?":
"Objects in JavaScript are handled by reference. A shallow copy, like spread or
Object.assign, creates a new top-level object but nested objects are still shared by reference, so changing a nested value in the copy changes the original. A deep copy recursively copies every level, so nothing is shared. Today the built-in way isstructuredClone(); the olderJSON.parse(JSON.stringify())trick loses functions,undefinedand dates, and fails on circular references."
Questions to prepare for:
"Write a deepClone function." Use recursion, handle
null, arrays and objects, and mention aMap/WeakMapfor circular references."Is
Object.assign()a deep copy?" No, shallow."What are the limitations of
JSON.parse(JSON.stringify())?" Loses functions andundefined, turns dates into strings,NaN/Infinityintonull, Map/Set into{}, throws on circular references andBigInt.Output questions like the opening example: after a spread copy, which changes affect the original?
Practice: predict the output, then run it.
const a = { x: 1, inner: { y: 2 }, list: [1, 2] };
const b = { ...a };
const c = structuredClone(a);
b.x = 10;
b.inner.y = 20;
c.list.push(3);
console.log(a.x, a.inner.y, a.list.length);(Answer: 1 20 2. b.x is a top-level primitive, b.inner is shared with a, and c is a fully separate deep copy.)
Conclusion
Copying an object is not the same as copying its contents at every level.
Primitives are copied by value; objects and arrays are handled by reference.
b = acopies nothing; both names point to the same object.A shallow copy (
...,Object.assign(),slice(),Array.from()) creates a new outer object but shares nested objects.A deep copy shares nothing. Use
structuredClone()for most data.JSON.parse(JSON.stringify())works only for plain JSON-like data.For state updates, shallow copy only along the path you change.
In the next chapter, we'll meet Map and Set, two built-in collections that you've already seen structuredClone() handle correctly.