Sub topic 1
Why Copying Objects Is Tricky: Values and References
Most bugs that make people search for "deep copy JavaScript" start with the same surprise. You change something that looks like a copy, and the original changes too. The cause is how JavaScript stores and passes values. Before looking at any copying technique, you need a clear picture of what a variable actually holds. This chapter builds that picture. Later chapters cover the specific tools: spread, the JSON round-trip and structuredClone.
Prerequisites
This chapter assumes you are comfortable with the following:
- JavaScript objects, arrays and the primitive types (
string,number,booleanand so on) - Object and array spread syntax (
{ ...obj },[...arr]) - Basic use of
Map,SetandDate - Running JavaScript in a browser console or with Node.js
try/catcherror handling
Every code block here runs as-is in Node.js 18 or later, or in a modern browser console. The comments show the expected output.
Two Kinds of Values
JavaScript has two families of values.
Primitives are string, number, bigint, boolean, undefined, null and symbol. A primitive is immutable: no operation can change it. Operations produce new primitives.
Objects are everything else: plain objects, arrays, functions, Date, Map, Set, class instances, typed arrays and so on. An object is a mutable structure that lives somewhere in memory. A variable never holds the object itself. It holds a reference, which is a pointer the engine uses to find the object.
The key rule follows from this. Assignment always copies what the variable holds. For a primitive, that is the value. For an object, that is the reference, so the object itself is not copied.
let a = 10;
let b = a;
b = 20;
console.log(a); // 10
console.log(b); // 20
const user = { name: 'Ada' };
const alias = user;
alias.name = 'Grace';
console.log(user.name); // 'Grace'
console.log(alias === user); // trueAssigning a to b gave b its own 10. Assigning user to alias gave alias a second reference to the same object. JavaScript only had one object, and it had two names for it.
Primitives Cannot Be Changed in Place
Strings can look like objects because they have methods, but they are primitives. A string method returns a new string and leaves the original alone.
let s = 'hello';
s.toUpperCase();
console.log(s); // 'hello'
s = s.toUpperCase();
console.log(s); // 'HELLO'The only way to "change" a primitive variable is to point it at a different value. That is why you never need to copy a primitive. Two variables can never share a primitive in a way that lets one of them change it for the other.
Identity Versus Equality
Because variables hold references, === compares references when both sides are objects. Two objects with identical contents are still different objects.
const x = { id: 1 };
const y = { id: 1 };
console.log(x === y); // false
console.log(x === x); // true
console.log('abc' === 'abc'); // true
console.log([1, 2] === [1, 2]); // falseThis is identity: whether two references point to the same object. Comparing contents is a different question. The language has no built-in deep-equality operator. Test libraries and helpers such as Node's util.isDeepStrictEqual fill that gap.
Identity matters for copying because it is how you check whether a copy really is separate. A true copy of an object should be !== to the original, and so should every nested object inside it. You will use that check throughout this tutorial.
Mutation Versus Reassignment
Two operations look alike in code but do very different things:
- Reassignment (
variable = something) changes which value a single variable holds. Other variables are not affected. - Mutation (
variable.prop = something,array.push(...)) changes the object itself. Every reference to that object sees the change.
let settings = { theme: 'dark' };
let saved = settings;
settings = { theme: 'light' }; // reassignment: settings now points elsewhere
console.log(saved.theme); // 'dark'
settings = saved;
settings.theme = 'light'; // mutation: changes the shared object
console.log(saved.theme); // 'light'When someone says "I changed the copy and the original changed," they almost always mutated an object that was shared through two references.
`const` Does Not Make Objects Immutable
const stops reassignment of the variable. It does nothing to stop mutation of the object the variable refers to.
const config = { retries: 3 };
config.retries = 5;
console.log(config.retries); // 5
try {
config = {};
} catch (err) {
console.log(err.name); // 'TypeError'
}Object.freeze blocks mutation, but only one level deep. Nested objects are separate objects reached through references, so freezing the outer object leaves them unfrozen.
const frozen = Object.freeze({ inner: { n: 1 } });
frozen.inner.n = 2;
console.log(frozen.inner.n); // 2
console.log(Object.isFrozen(frozen)); // true
console.log(Object.isFrozen(frozen.inner)); // falseThis is the same "only the top level" pattern you will meet again with shallow copies in the next chapter.
Passing Objects to Functions
Function arguments follow the assignment rule. The parameter receives a copy of what the caller passed. For an object, that is a copy of the reference. This model is often called call by sharing. It is neither classic pass-by-reference nor a full copy of the object.
function rename(person) {
person.name = 'Changed'; // mutation: the caller sees this
person = { name: 'Replaced' }; // reassignment: only the local variable changes
}
const p = { name: 'Ada' };
rename(p);
console.log(p.name); // 'Changed'The function could mutate the caller's object, but it could not make the caller's variable point to a new object. If JavaScript were truly pass-by-reference, p.name would be 'Replaced'.
In practice, this means any function you pass an object to can change your data. Code that must not change its inputs needs to avoid mutation or work on a copy.
Common Ways Shared References Bite
The following mistakes show up again and again in real code. Each has the same root cause.
Filling an Array with One Object
Array.prototype.fill puts the same value into every slot. When that value is an object, every slot holds a reference to the same object.
const grid = new Array(3).fill([]);
grid[0].push('x');
console.log(grid); // [ [ 'x' ], [ 'x' ], [ 'x' ] ]
console.log(grid[0] === grid[2]); // true
const fixed = Array.from({ length: 3 }, () => []);
fixed[0].push('x');
console.log(fixed); // [ [ 'x' ], [], [] ]Array.from with a factory function calls the function once per slot, so each slot gets a fresh array.
Methods That Mutate in Place
Some array methods change the array they are called on and return that same array. The return value looks like a new result, but it is the original.
const scores = [3, 1, 2];
const sorted = scores.sort();
console.log(scores); // [ 1, 2, 3 ]
console.log(sorted === scores); // truesort, reverse, splice, fill, push, pop, shift and unshift all mutate. Newer runtimes provide non-mutating versions: toSorted, toReversed, toSpliced and with (Node.js 20+, current browsers).
Shared Defaults and Module-Level State
An object created once and handed out many times is shared by everyone who receives it.
const DEFAULTS = { tags: [] };
function makePost(title) {
return { title, tags: DEFAULTS.tags };
}
const first = makePost('One');
const second = makePost('Two');
first.tags.push('news');
console.log(second.tags); // [ 'news' ]
console.log(DEFAULTS.tags); // [ 'news' ]Each post looks independent, but they all share one tags array. The defaults object itself now holds 'news'.
Accidental Mutation of Inputs and State
UI frameworks such as React decide whether to re-render by comparing references. If you mutate an array in state and pass the same reference back, the framework sees oldState === newState and may skip the update. The opposite mistake also happens. You keep a "snapshot" of earlier state for undo, and later mutations change the snapshot through a shared nested object.
Three Levels of Copying
Once you see values as references, "copy" can mean three different things. The rest of this tutorial depends on these terms.
| Operation | What is new | What is shared with the original | Example |
|---|---|---|---|
| Reference copy | Nothing; only a new variable | The whole object | `const b = a;` |
| Shallow copy | The top-level object | Every nested object and array | `const b = { ...a };` |
| Deep copy | The top-level object and every nested object | Nothing (only primitives, which are safe) | `const b = structuredClone(a);` |
A shallow copy is enough when the object holds only primitives, or when you never mutate the nested parts. A deep copy is what you need when you plan to change nested data on one side without affecting the other. Deep copying is harder than it looks. A deep copy has to handle Date, Map, Set, typed arrays, objects that refer to themselves, and values like functions that cannot be copied in any meaningful way. The coming chapters work through these cases. They start with shallow copies, then cover the JSON round-trip and its limits, then structuredClone.
A Mental Checklist
Before you change an object, ask these questions:
- Did I create this object, or was it handed to me? If it was handed to me, someone else may hold a reference.
- Am I reassigning a variable or mutating an object? Only mutation affects other references.
- Does this object contain other objects? If so, copying only the top level leaves those inner objects shared.
- Does the method I am calling mutate in place, or does it return a new value?
These questions explain almost every "my copy changed the original" bug. They also tell you which level of copy a situation needs.
Exercise
Predict the three logged values, then explain each one. const a = { list: [1] }; let b = a; b.list.push(2); b = { list: [9] }; console.log(a.list, b.list, a === b);
Show answer
The output is [ 1, 2 ] [ 9 ] false. The line let b = a copies the reference, so b.list.push(2) mutates the one shared array and a.list becomes [1, 2]. Then b = { list: [9] } reassigns b to a brand-new object, which does not affect a. After that, a and b refer to different objects, so a === b is false.
Exercise
A function addItem(cart, item) is supposed to return a new cart without changing the caller's cart. It is written as cart.items.push(item); return cart;. Explain why the caller's cart changes, and whether replacing the body with return { ...cart, items: cart.items }; fixes it.
Show answer
The parameter cart holds a copy of the caller's reference, so cart.items.push(item) mutates the caller's own items array, and the function returns the same object. The proposed replacement creates a new top-level object, but items: cart.items still points to the original array. It also never adds the item. A working version creates a new array as well, for example return { ...cart, items: [...cart.items, item] };.
Exercise
Why does Object.freeze(state) not stop state.user.name = 'X' from succeeding, and what does this have in common with a shallow copy?
Show answer
Object.freeze only blocks changes to the frozen object's own properties. state.user holds a reference to a separate object, and that object is not frozen, so you can still change its properties. A shallow copy has the same limit. Both operations act on the top-level object only and leave nested objects reachable through the same references.