06 Immutability
Lesson goal Learn to update objects and arrays without mutation, by copying with spread and structuredClone, with non-mutating array methods and with Ramda functions, and understand where a copy is shallow and what it costs.
Immutable data does not change after it is created: to "change" an object, you create a new one, and the previous one stays as it was. The "Pure functions" lesson already did this: changeAge returned a new user via spread. Here we look at why this is needed, where a copy turns out shallow, how to guard against accidental mutation, and what copies cost.
Why mutation breaks predictability
A variable holding an object or an array holds a reference to it, and assignment or passing it to a function copies the reference, not the object itself. So a variable, a function argument and a field of another object can all point to the same object. If one part of the program changes it, every other part sees the change, and the bug shows up far from where the mutation happened: to find it, you have to work out who else holds a reference to that object.
// Mutating an argument
// ===============================
// bestScoreImpure :: [Number] -> Number
// IMpure: sort sorts the array that was passed in
const bestScoreImpure = (scores) => scores.sort((a, b) => b - a)[0]
const scores = [40, 95, 70]
console.log(bestScoreImpure(scores)) // 95
console.log(scores) // [95, 70, 40]: the original order is lost
// A shared object
// ===============================
const defaults = { theme: 'light', fontSize: 14 }
const userSettings = defaults // the reference is copied, not the object
userSettings.theme = 'dark'
console.log(defaults.theme) // dark: the defaults have changed too
// Without mutation
// ===============================
const baseSettings = { theme: 'light', fontSize: 14 }
const darkSettings = { ...baseSettings, theme: 'dark' } // a new object
console.log(`${baseSettings.theme} -> ${darkSettings.theme}`) // light -> darkconst does not help here: it forbids assigning another value to the variable but does not prevent changing the object it points to. Declaring const defaults does not make the object immutable; that takes a copy or Object.freeze.
Shallow and deep copies
Spread creates a new object ({ ...obj }) or array ([...arr]) but copies only the top level: nested objects and arrays stay shared with the original. The same is true of Object.assign({}, obj), arr.slice() and Array.from(arr). To change a nested field safely, you copy every level on the path to it and take the other branches as they are. This is called structural sharing: the new object shares with the old one everything that has not changed.
// A shallow copy
// ===============================
const user = { name: 'Anna', address: { city: 'Moscow' }, tags: ['js'] }
const shallow = { ...user }
shallow.name = 'Olga' // the top level was copied: user keeps its name
shallow.address.city = 'Kazan' // address is shared: the city changes for user too
console.log(user.name) // Anna
console.log(user.address.city) // Kazan
// Copying every level on the path to the change
// ===============================
const original = { name: 'Anna', address: { city: 'Moscow' }, tags: ['js'] }
const moved = {
...original,
address: { ...original.address, city: 'Kazan' },
}
console.log(original.address.city) // Moscow
console.log(moved.address.city) // Kazan
console.log(moved.tags === original.tags) // true: the unchanged branch is shared
// A deep copy
// ===============================
const deep = structuredClone(original)
deep.tags.push('fp')
console.log(original.tags) // ["js"]
console.log(deep.tags) // ["js", "fp"]structuredClone copies the whole structure to any depth: nested objects and arrays, Date, Map, Set and even circular references. It cannot copy functions and throws a DataCloneError, and a class instance turns into a plain object: the class prototype and methods are lost. JSON.parse(JSON.stringify(obj)) loses more: a Date becomes a string, Map and Set become empty objects, fields holding undefined or functions disappear, and NaN turns into null. structuredClone is available in all major browsers since 2022 and in Node.js since version 17.
Object.freeze
Object.freeze forbids adding, deleting and changing an object's properties and returns the same object. Freezing is shallow: nested objects stay mutable and are frozen separately. What happens on an attempt to write depends on the mode: in sloppy (non-strict) mode the assignment is silently ignored, in strict mode a TypeError is thrown. Code in the course playground runs in non-strict mode, while the code of ES modules (files with import and export) and of class bodies is always strict: there the same write throws a TypeError.
// Object.freeze
// ===============================
const config = Object.freeze({ mode: 'prod', limits: { requests: 100 } })
// non-strict mode: the assignment is silently ignored
config.mode = 'dev'
console.log(config.mode) // prod
// strict mode: the same write throws a TypeError
const setModeStrict = () => {
'use strict'
config.mode = 'dev'
}
try {
setModeStrict()
} catch (error) {
console.log(`strict mode: ${error.name}`) // strict mode: TypeError
}
// array methods throw a TypeError in any mode
const frozenList = Object.freeze([1, 2])
try {
frozenList.push(3)
} catch (error) {
console.log(`push: ${error.name}`) // push: TypeError
}
// freezing is shallow: the nested object can still be changed
config.limits.requests = 1
console.log(config.limits.requests) // 1
console.log(`config: ${Object.isFrozen(config)}, limits: ${Object.isFrozen(config.limits)}`) // config: true, limits: falseThe exception to the non-strict rule is built-in methods: push, sort and other mutating methods on a frozen array always throw a TypeError, because the specification requires them to fail when a write does not succeed. Object.freeze helps catch accidental mutation, but it makes no copies: a new value is still created with spread or structuredClone.
Non-mutating array methods
Some array methods change the array itself: push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin. Others return a new array and leave the original alone: map, filter, concat, slice. ES2023 added non-mutating versions of sorting, reversing, splice and replacing an element.
| Task | Changes the array | Returns a new array |
|---|---|---|
| Append | push(x) | concat(x) or [...arr, x] |
| Sort | sort(fn) | toSorted(fn) or [...arr].sort(fn) |
| Reverse | reverse() | toReversed() or [...arr].reverse() |
| Remove or insert elements | splice(start, count, ...items) | toSpliced(start, count, ...items) or slice and spread |
| Replace an element | arr[i] = x | with(i, x) or map |
toSorted, toReversed, toSpliced and with became part of the ES2023 standard. They are supported by Chrome and Edge from version 110, Firefox from 115, Safari from 16 and Node.js from 20. If a project has to run in older browsers, copy the array and call the mutating method on the copy ([...arr].sort(fn)), or add a polyfill.
// Non-mutating array methods
// ===============================
const scores = [40, 95, 70]
// bestScore :: [Number] -> Number
// toSorted from ES2023 sorts a copy; without ES2023 the same is [...list].sort((a, b) => b - a)[0]
const bestScore = (list) => list.toSorted((a, b) => b - a)[0]
console.log(bestScore(scores)) // 95
const added = scores.concat(60) // instead of push
const replaced = scores.with(1, 90) // instead of scores[1] = 90
const withoutFirst = scores.toSpliced(0, 1) // instead of splice(0, 1)
const reversed = scores.toReversed() // instead of reverse()
console.log(added) // [40, 95, 70, 60]
console.log(replaced) // [40, 90, 70]
console.log(withoutFirst) // [95, 70]
console.log(reversed) // [70, 95, 40]
console.log(scores) // [40, 95, 70]: the original array has not changedRamda: assoc, assocPath and evolve
Ramda functions do not change their arguments. R.assoc(key, value, obj) returns a copy of the object with the key set to a new value, R.assocPath(path, value, obj) does the same along a nested path, and R.evolve(transformations, obj) applies functions to the listed keys, nested ones included, and leaves the rest as they are. Only the objects on the path to the change are copied; the other branches are shared with the original object, just as with spread by hand. Lenses generalize this idea; they have a lesson of their own, "Lenses".
// assoc, assocPath and evolve come from Ramda: the course playground exposes it as R
// ===============================
const post = {
title: 'Immutability',
author: { name: 'Anna', city: 'Moscow' },
stats: { views: 10, likes: 2 },
tags: ['js'],
}
// R.assoc: a copy with a new value for the key
const renamed = R.assoc('title', 'Immutable data', post)
// R.assocPath: a copy with a new value along a nested path
const moved = R.assocPath(['author', 'city'], 'Kazan', post)
// R.evolve: functions for the keys you need, the other keys stay as they are
const viewed = R.evolve({ stats: { views: (n) => n + 1 }, tags: (tags) => [...tags, 'fp'] }, post)
console.log(renamed.title) // Immutable data
console.log(moved.author.city) // Kazan
console.log(viewed.stats.views) // 11
console.log(viewed.tags) // ["js", "fp"]
// the original post has not changed
console.log(`${post.title}, ${post.author.city}, ${post.stats.views}, ${post.tags.length}`) // Immutability, Moscow, 10, 1
// the unchanged branches are shared with the original post
console.log(moved.stats === post.stats) // true
console.log(viewed.author === post.author) // trueThe cost of copying
A copy is not free: spread walks over every key or element of the top level, and structuredClone over the whole structure. For a single update this goes unnoticed, but in a loop the copies add up. A common trap is reduce with the accumulator [...acc, x]: every step copies the whole accumulated array, so n elements add up to about n²/2 element copies. For 1,000 elements that is 499,500 copies, for 10,000 it is almost 50 million.
Immutability matters at the boundaries, where someone else can see the data. An array that a function created itself and has not handed to anyone yet can safely be filled with push: nobody outside can see it, and the function stays pure. For large, frequently updated collections there are libraries built on structural sharing: Immutable.js with persistent data structures, and Immer, where you write ordinary "mutating" code against a draft and get a new object back.
Key points
- Assignment and passing to a function copy the reference to an object, not the object itself: a mutation in one place is visible wherever there is a reference to the same object. const forbids reassignment, not changing the object.
- Spread, Object.assign and slice copy only the top level. For a nested change, copy every level on the path to it; for a full copy there is structuredClone.
- Object.freeze is shallow: in non-strict mode a write to a frozen property is silently ignored, in strict mode it throws a TypeError.
- Instead of push, sort, reverse and splice, use concat, slice and spread, or the ES2023 methods toSorted, toReversed, toSpliced and with. R.assoc, R.assocPath and R.evolve update objects without mutation.
- Copies cost time and memory: [...acc, x] in reduce leads to quadratic complexity. A local array that nobody else can see yet may be filled with push.
Exercises
Exercise 1
The addScoreImpure and topThreeImpure functions change the array passed to them. Write pure addScore and topThree: the first returns a new array with the score added, the second returns the three best scores in descending order. The original scores array must stay the same.
Starter code
// addScoreImpure :: ([Number], Number) -> [Number]
// IMpure: push changes the array passed in
const addScoreImpure = (scores, score) => {
scores.push(score)
return scores
}
// topThreeImpure :: [Number] -> [Number]
// IMpure: sort sorts the array passed in
const topThreeImpure = (scores) => scores.sort((a, b) => b - a).slice(0, 3)
// addScore :: ([Number], Number) -> [Number]
// topThree :: [Number] -> [Number]
// your code
const scores = [40, 95, 70, 85]
const updated = addScore(scores, 60)
console.log(`top three: ${topThree(updated).join(', ')}`)
console.log(`original array: ${scores.join(', ')}`)
console.log(`new array: ${updated.join(', ')}`)Expected output
top three: 95, 85, 70 original array: 40, 95, 70, 85 new array: 40, 95, 70, 85, 60
Show solution
// addScoreImpure :: ([Number], Number) -> [Number]
// IMpure: push changes the array passed in
const addScoreImpure = (scores, score) => {
scores.push(score)
return scores
}
// topThreeImpure :: [Number] -> [Number]
// IMpure: sort sorts the array passed in
const topThreeImpure = (scores) => scores.sort((a, b) => b - a).slice(0, 3)
// addScore :: ([Number], Number) -> [Number]
// a new array instead of push
const addScore = (scores, score) => [...scores, score]
// topThree :: [Number] -> [Number]
// we sort a copy; in ES2023 scores.toSorted((a, b) => b - a) does the same
const topThree = (scores) => [...scores].sort((a, b) => b - a).slice(0, 3)
const scores = [40, 95, 70, 85]
const updated = addScore(scores, 60)
console.log(`top three: ${topThree(updated).join(', ')}`)
console.log(`original array: ${scores.join(', ')}`)
console.log(`new array: ${updated.join(', ')}`)Exercise 2
The moveToImpure function changes the city right inside the state passed to it. Write a pure moveTo(city, state): use spread to copy every level on the path state.user.address. Then write moveToRamda with the same result using R.assocPath. Check that the original state has not changed, the user object is new, and the cart branch you did not touch is still shared.
Starter code
const state = {
user: { name: 'Anna', address: { city: 'Moscow', zip: '101000' } },
cart: [{ title: 'book', qty: 1 }],
}
// moveToImpure :: (String, Object) -> Object
// IMpure: it changes the state passed in
const moveToImpure = (city, state) => {
state.user.address.city = city
return state
}
// moveTo :: (String, Object) -> Object
// moveToRamda :: (String, Object) -> Object
// your code: moveTo with spread, moveToRamda with R.assocPath
const next = moveTo('Kazan', state)
console.log(`before: ${state.user.address.city}, after: ${next.user.address.city}`)
console.log(`new user: ${next.user !== state.user}`)
console.log(`shared cart: ${next.cart === state.cart}`)
console.log(`R.assocPath gives the same: ${JSON.stringify(moveToRamda('Kazan', state)) === JSON.stringify(next)}`)Expected output
before: Moscow, after: Kazan new user: true shared cart: true R.assocPath gives the same: true
Show solution
const state = {
user: { name: 'Anna', address: { city: 'Moscow', zip: '101000' } },
cart: [{ title: 'book', qty: 1 }],
}
// moveToImpure :: (String, Object) -> Object
// IMpure: it changes the state passed in
const moveToImpure = (city, state) => {
state.user.address.city = city
return state
}
// moveTo :: (String, Object) -> Object
// new objects only on the path state -> user -> address, cart is taken as it is
const moveTo = (city, state) => ({
...state,
user: {
...state.user,
address: { ...state.user.address, city },
},
})
// moveToRamda :: (String, Object) -> Object
const moveToRamda = (city, state) => R.assocPath(['user', 'address', 'city'], city, state)
const next = moveTo('Kazan', state)
console.log(`before: ${state.user.address.city}, after: ${next.user.address.city}`)
console.log(`new user: ${next.user !== state.user}`)
console.log(`shared cart: ${next.cart === state.cart}`)
console.log(`R.assocPath gives the same: ${JSON.stringify(moveToRamda('Kazan', state)) === JSON.stringify(next)}`)Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.