Immutability means representing data so its values are not modified after creation. Instead of changing existing data, code creates and returns a changed version. This separates stable data from actions that interact with the outside world, making calculations easier to test and reuse. section 2.7 section 6.20
Apply immutability through a small set of practical disciplines:
- Use copy-on-write: make a shallow copy, modify the copy, and return it instead of changing the original. section 4.10 section 6.20
- Use structural sharing when a shallow copy can reuse references to unchanged nested values. section 6.13
- Use defensive copying when interacting with untrusted code; it protects immutability more powerfully but copies more data. section 7.12
- Keep mutable state safer by storing immutable values and updating them through calculations that return valid replacements. section 18.9
Replacing a mutable cart update
A mutating implementation calls `cart.push(...)`. An immutable version copies the array with `cart.slice()`, pushes the new item into that copy, and returns it. The caller assigns the returned cart, turning the update into an explicit result rather than an implicit output. section 4.10 section 5.8
function add_item(cart, name, price) {
var new_cart = cart.slice(); #1
new_cart.push({ #2
name: name,
price: price
}); return new_cart; #3
}
Inspect the JavaScript copy-on-write implementation that creates a new cart, adds an item, and returns the new value. section 5.8























