Sub topic 1
Why Copying Objects Is Tricky: Values and References
When you write const b = a, JavaScript does something different depending on what a holds. For a number or a string, you get an independent value. For an object or an array, you get a second name for the same thing. That difference causes most copying bugs, and it is the reason structuredClone exists.
Prerequisites
This chapter assumes you already know:
- JavaScript objects, arrays and primitive types
- Object and array spread syntax
- Basic use of
Map,SetandDate - How to run JavaScript in a browser console or Node.js
try/catcherror handling
You can run every example here as written in Node.js or a browser console.
Primitives Are Copied by Value
JavaScript has seven primitive types: string, number, bigint, boolean, undefined, symbol and null. Primitives are immutable. No operation can change the value 5 or the string 'Ada'. Code that looks like it changes a primitive is really putting a new value into the variable.
let a = 5;
let b = a;
b = b + 1;
console.log(a); // 5
console.log(b); // 6
let name = 'Ada';
let other = name;
other = other.toUpperCase();
console.log(name); // 'Ada'
console.log(other); // 'ADA'Changing b and other never affects a and name, because the variables do not share anything you can modify.
Objects Are Shared by Reference
Every other value is an object. That includes plain objects, arrays, functions, Date, Map and Set. A variable that holds an object holds a reference, which is a pointer to where the object lives in memory. Assigning that variable to another one copies the reference. The object itself is not copied.
const user = { name: 'Ada', roles: ['admin'] };
const alias = user;
alias.name = 'Grace';
alias.roles.push('editor');
console.log(user.name); // 'Grace'
console.log(user.roles); // ['admin', 'editor']
console.log(alias === user); // trueuser and alias are two labels on one object. Any change made through either label shows up through the other.
Equality Compares Identity
The === operator follows the same rule. Primitives are equal when their values match. Objects are equal only when both sides are the same object.
console.log('Ada' === 'Ada'); // true
console.log({ x: 1 } === { x: 1 }); // false: two separate objects
console.log([1, 2] === [1, 2]); // false
const p = { x: 1 };
const q = p;
console.log(p === q); // true: same referenceThis explains why === cannot tell you whether a copy worked. It only tells you whether two references point to the same object.
Passing Objects to Functions
Function arguments are passed the same way as assignment. A function that receives an object gets a copy of the reference, so if it mutates that object, the caller sees the change.
function addTag(post, tag) {
post.tags.push(tag);
return post;
}
const draft = { title: 'Hello', tags: [] };
const published = addTag(draft, 'news');
console.log(draft.tags); // ['news']
console.log(published === draft); // trueReassigning the parameter inside the function is different. post = {} points the local name at a new object and leaves the caller's object alone. Only mutation goes through the shared reference.
The Three Kinds of "Copy"
When people say they copied an object, they can mean any of these:
| Kind | What is new | What is shared | Example |
|---|---|---|---|
| Reference copy | Nothing | The whole object | `const b = a` |
| Shallow copy | The top-level container | Every nested object | `{ ...a }`, `[...a]` |
| Deep copy | The container and everything nested inside it | Nothing | `structuredClone(a)` |
Shallow copies are covered in the next chapter. A deep copy is the only one of these that lets you change any part of the copy without touching the original. The rest of this tutorial explains how to make one correctly.
Exercise
After running const a = { n: 1, list: [1] }; const b = a; b.n = 2; b = null; what happens, and what would a contain if the last statement were removed?
Show answer
b = null throws a TypeError because b is declared with const. Without that line, a is { n: 2, list: [1] }, because b and a refer to the same object and b.n = 2 mutated it.
Exercise
A function reset(config) runs config = { debug: false }. Does the caller's object change? What if it ran config.debug = false instead?
Show answer
Reassigning config only changes the local parameter, so the caller's object is unchanged. Setting config.debug = false mutates the shared object, so the caller sees debug become false.