JavaScript 09 · JavaScript for React
References and immutability
Value vs. reference, shallow copies, nested updates without mutation – and why React depends on it.
Loading lesson…
JavaScript 09 · JavaScript for React
Value vs. reference, shallow copies, nested updates without mutation – and why React depends on it.
Loading lesson…
The previous lessons were general JavaScript. This one and the next are about the JavaScript that React requires. Skip them and you'll meet mysterious bugs in React: "I changed the data but the page didn't re-render" or "I changed one thing and something else broke".
Both bugs have the same cause: not understanding how JavaScript treats objects and arrays. Twins look the same, but they're two different people. And one person can have two nicknames, but it's still one person. This is exactly where JavaScript treats objects differently from numbers and text.
Primitive values (numbers, text, booleans) are copied when assigned. Each variable has its own:
let a = 5let b = a // b gets a COPY of the value 5b = 10a // 5 – a didn't change
Objects and arrays behave differently. The variable doesn't hold the object itself, but a tag with the address where the object lives. Assignment copies just the tag – both variables then lead to the same house:
const a = { count: 1 }const b = a // b is NOT a copy – it's a second tag with THE SAME addressb.count = 99a.count // 99 😱 "a" changed too – it's the same objectconst list = [1, 2]const sameList = listsameList.push(3)list // [1, 2, 3]
| Primitive values | Objects, arrays, functions | |
|---|---|---|
| Examples | 5, 'hello', true, null | { … }, [ … ], () => … |
| Assignment b = a | copies the value | copies the reference (the address) |
| a === b compares | the value | whether it’s THE SAME object |
| Can they be changed “inside”? | no (5 is simply 5) | yes (properties, items) |
'hello' === 'hello' // true – the same value[1, 2] === [1, 2] // false – two different arrays (two addresses) that just look the same{ a: 1 } === { a: 1 } // falseconst x = { a: 1 }const y = xx === y // true – the same address// Comparing by content is up to youx.a === y.a // compares the values of the properties – those are numbers, so trueconst arr1 = [1, 2]const arr2 = [1, 2]JSON.stringify(arr1) === JSON.stringify(arr2) // true – a quick (but imperfect) content check
The last line turns both arrays into text (JSON.stringify from lesson JavaScript 08) and compares two pieces of text – and text is compared by value. It's imperfect because with objects the order of the properties matters: { a: 1, b: 2 } and { b: 2, a: 1 } give two different texts, even though they hold the same thing.
Mutation means changing an existing object or array "inside" – overwriting a property, adding an item, sorting in place. The trouble starts when several places in the code share that object:
// An array of products in the order they appear in the catalogueconst catalog = [{ name: 'Bike', price: 400 },{ name: 'Bell', price: 8 },{ name: 'Helmet', price: 50 },]// ❌ Not like thisfunction sortByPrice(products) {return products.sort((a, b) => a.price - b.price) // sort reorders the ORIGINAL array and returns it}const cheapFirst = sortByPrice(catalog) // Bell, Helmet, Bike – what we wantedcatalog // Bell, Helmet, Bike 😱 the catalogue got reshuffled toocheapFirst === catalog // true – it's still one and the same array// ✅ Like thisfunction sortByPrice(products) {return products.toSorted((a, b) => a.price - b.price) // toSorted makes a NEW sorted array}
Why did the catalogue get reshuffled? When you call a function, only the address label is copied into the parameter products – products and catalog lead to the same house. And sort (from lesson JavaScript 05) doesn't make a new array, it reorders the items in the original one. So the function changed data that isn't its own "behind your back", and anyone who keeps using catalog suddenly gets a different order. toSorted sorts the same way, only into a new array, and leaves the original alone.
The table shows the most common mutations (on the left) and for each one a replacement that returns a new object or array instead of changing anything and leaves the original as it was (on the right). You already know all the replacements: spread and destructuring with ...rest from lesson JavaScript 03, filter and map from lesson JavaScript 04, and toSpliced, with, toSorted and toReversed from lesson JavaScript 05.
| ❌ Mutates | ✅ Makes something new |
|---|---|
obj.name = 'x' | { ...obj, name: 'x' } |
delete obj.name | const { name, ...rest } = obj |
arr.push(x) | [...arr, x] |
arr.splice(i, 1) | arr.filter(…) / arr.toSpliced(i, 1) |
arr[i] = x | arr.map(…) / arr.with(i, x) |
arr.sort() | arr.toSorted() |
arr.reverse() | arr.toReversed() |
Two rows are worth explaining: const { name, ...rest } = obj takes name out into a variable and gathers everything else into a new object rest – that's the object "without name", and obj stays whole. And arr.toSpliced(i, 1) returns a new array in which 1 item is missing from position i.
What you see: Two buttons, two ways to get an array with an extra plum. Below them, a printout of both arrays.
Try it:
fruits too, and next === fruits is true.next === fruits is false.The takeaway: Assignment doesn't copy. A new array (or object) is only created by spread, map, filter and similar methods – and that's the only kind of change React notices.
Loading the interactive part…
Spread makes a shallow copy: a new object on the first level, but the nested objects are still the same. Like photocopying a list of addresses – the paper is new, but the houses at the addresses are the same.
const user = { name: 'Anna', address: { city: 'London' } }const copy = { ...user }copy === user // false – a new objectcopy.address === user.address // true – the nested object is SHAREDcopy.name = 'Eve' // user.name stays 'Anna' ✅copy.address.city = 'Boston' // user.address.city is 'Boston' too 😱
Why? Spread takes the properties of the object and copies them into a new object – but the value of the property address is itself just an address label. So the new object gets a copy of the label, not a copy of the address object itself.
A deep copy copies the object and everything nested in it, down to the last level. Then nothing is shared.
const deep = structuredClone(user) // copies everything all the way downdeep.address === user.address // false – the address is a new object toodeep.address.city = 'Boston' // user.address.city stays 'London' ✅// The older trick: object → text → object againconst deep2 = JSON.parse(JSON.stringify(user))
structuredClone is a function built into JavaScript in the browser (nothing to import): it goes through the object to every level and makes a copy of each nested object and array. The older trick turns the object into text and that text back into an object (JSON.stringify and JSON.parse from lesson JavaScript 08) – the text becomes brand-new objects. But JSON only knows text, numbers, booleans, null, arrays and objects: a date (Date) turns into plain text on the way, and functions and properties set to undefined disappear completely.
You'll write these patterns in React again and again – on every state change. They're worth having at your fingertips. Every line returns a new object or array and leaves the original user or todos unchanged.
const user = { name: 'Anna', age: 31, address: { city: 'London', zip: 'SW1A 1AA' } }{ ...user, age: 32 } // change a property{ ...user, email: 'anna@example.com' } // add a propertyconst { age, ...withoutAge } = user // remove a property: withoutAge = everything except age{ ...user, [field]: value } // change the property whose name is in the variable field{ ...user, address: { ...user.address, city: 'Boston' } } // change a nested one – spread on every level{ ...user, age: user.age + 1 } // derive from the previous value: 31 + 1 = 32
A spread followed by a property works like this: first all the old properties are copied, then the one after the comma overwrites the property of the same name (or adds a new one). [field] in square brackets is from lesson JavaScript 03: the property name is taken from a variable, so when field holds 'email', email changes. The hardest one is the nested change, here step by step:
const moved = {...user, // 1. a new user object with all the old properties (including the label of the old address)address: { // 2. in it we overwrite the property address with a NEW address object,...user.address, // into which we copy everything from the old address (city and zip)city: 'Boston', // 3. and in that one we overwrite only city},}// moved.address = { city: 'Boston', zip: 'SW1A 1AA' }, user.address stayed { city: 'London', zip: 'SW1A 1AA' }// ❌ Not like this: without ...user.address the zip is lost{ ...user, address: { city: 'Boston' } } // address = { city: 'Boston' } – zip is gone
const todos = [{ id: 1, title: 'Go shopping', done: false },{ id: 2, title: 'Tidy up', done: true },]const newTodo = { id: 3, title: 'Take out the bin', done: false } // a new todo we're addingconst id = 2 // the id of the todo we want to do something with – here “Tidy up”const newTitle = 'Tidy up the room' // the new title for the todo with this id// In an app the id would come from outside – e.g. as a parameter of a function that a click on a todo's “Delete” calls.// Every line returns a NEW array and leaves todos unchanged (after → is what the new array holds):[...todos, newTodo] // add to the end// → Go shopping, Tidy up, Take out the bin[newTodo, ...todos] // add to the start// → Take out the bin, Go shopping, Tidy uptodos.toSpliced(1, 0, newTodo) // insert: at position 1, delete 0 items, insert newTodo// → Go shopping, Take out the bin, Tidy uptodos.filter((t) => t.id !== id) // remove by id: keep only the todos whose id is NOT 2// → Go shoppingtodos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)) // change one item (flip done)// → Go shopping (done: false), Tidy up (done: false – it was true)todos.map((t) => (t.id === id ? { ...t, title: newTitle } : t)) // rename one// → Go shopping, Tidy up the roomtodos.map((t) => ({ ...t, done: true })) // change all of them// → Go shopping (done: true), Tidy up (done: true)todos.filter((t) => !t.done) // remove all the finished ones// → Go shoppingtodos.toSorted((a, b) => a.title.localeCompare(b.title)) // sort alphabetically (lesson JavaScript 05)// → Go shopping, Tidy up (already in order, but it's a new array)
The most common one is "change one item". Read it like this: map goes through all the todos and builds a new array from whatever it returns for each one. For every todo t it asks with a ternary (from lesson JavaScript 06): is this the one with the id we're looking for? If yes, it returns { ...t, done: !t.done } – a new object, a copy of the todo with done flipped (! turns true into false and back). If not, it returns the original t unchanged. In map((t) => ({ … })) the object is wrapped in round brackets so JavaScript knows the curly braces are an object and not the function body (lesson JavaScript 02).
const board = {title: 'Project',columns: [{ id: 'todo', cards: [{ id: 1, text: 'A' }] },{ id: 'done', cards: [] },],}// Add a card to the 'done' columnconst newCard = { id: 2, text: 'B' }const next = {...board, // 1. a new boardcolumns: board.columns.map((col) => // 2. a new array of columnscol.id === 'done'? { ...col, cards: [...col.cards, newCard] } // 3. a new column with a new array of cards: col, // the other columns unchanged),}
Here the path to the change goes through three levels: the board → the array columns → the column 'done' → its array cards. Read the code from the outside in: (1) ...board copies the board, but we overwrite the property columns right away. (2) The new array of columns is made by map; for every column the ternary asks whether it's 'done'. (3) For the column 'done' it returns a copy with a new array of cards – the old cards and newCard after them. The other columns (: col) come back unchanged. The result: next, next.columns and the column 'done' are new objects, the column 'todo' is still the original one.
The procedure is always the same: follow the path to the change and make a copy on every level; leave everything off the path as it is. When the nesting gets too deep, it's a sign the state could be organised more flatly (lessons React basics 04 and Hooks 03).
Data that changes on the page (a list of todos, say) is kept by React in state. You met the function useState in lesson JavaScript 03: it returns the current value and a function to set it (here setTodos). When you call that function, React compares the old and the new value with === (more precisely with the function Object.is, which differs from === only in two edge cases with numbers – for objects and arrays it's the same). When it's the same object, it concludes nothing has changed and doesn't redraw that part of the page (the component). Arrays and objects in state get a lesson of their own: React basics 04.
// An example from lesson React basics 04 – state with an array of todos (an empty array to start with)const [todos, setTodos] = useState([])const newTodo = { id: 1, title: 'Go shopping', done: false } // the todo we want to add// ❌ Mutation: the array is still THE SAME, React notices nothing, the page doesn't changetodos.push(newTodo)setTodos(todos)// ✅ A new array: React sees a different address → re-renderssetTodos([...todos, newTodo])
memo and useMemo (Advanced React 04) skip needless work when the data hasn't changed, and effects (Hooks 01) run their code again only when the values they depend on change. Both only work because unchanged data keep the same address and changed data get a new one.Add an item to an array and rename a user – each time so that a new array or a new object is created.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The first challenge practises the basic immutable updates on simple data. The second goes deeper: state with projects and tasks, where the tests use === to check that you copy only what's necessary – exactly like React.
Six small functions that return new data instead of changing the old. You'll write exactly such functions for changing state in the next lessons. What exactly each one should return is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The app state with a user, projects and tasks. Write six functions that change one thing in it – and leave everything else as the same objects. The whole state and what each function should change are in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
=== on objects compares the address, not the content. Two objects that look the same aren't "the same".{ ...obj, key: value }.