These are the notes for JavaScript episode 29. Until now our bugs have been loud: red text, a crash, an error name. Today's bug is silent. A Diwali offer function gives Asha 10% off her masala dosa and filter coffee, and then the menu itself says 72 and 27 for every customer after her. Nobody else asked for the offer. The function quietly changed data that didn't belong to it. So you'll invent the habits that make this kind of bug impossible: pure functions (same input, same output, no side effects), returning new data with map and spread instead of changing the old data, and immutability (treating data as read only). Along the way you'll find out that const does not lock your data (TypeError: Assignment to constant variable. only fires when you re-point the name), that Object.freeze does lock it but silently until strict mode makes it shout (TypeError: Cannot assign to read only property 'price' of object '#<Object>'), that both freeze and spread are shallow, that structuredClone copies all the way down, that sort changes your array and sorts numbers as text ([ 100, 25, 250, 9 ]), and that toSorted, toReversed and with give you safe copies. Finally you'll build prices from small pure steps, discount(10), addGst, round, snapped together with pipe. Every output below is real Node.js output (node main.js, Node 24).
Builds on: variables and const (episode 2), arrays and sort (7), objects and copying by reference (8), functions and arrow functions (9), closures (10), map, filter and reduce (11), spread and rest (12), errors (13). Leads to: testing with node:test (30).
The real-life idea: the photocopy, not the register
Every school class has one attendance register. There is only one copy, and every teacher reads the same one.
- If the maths teacher scribbles practice-test marks into the register, every other teacher now sees those wrong marks. Nobody asked for that change; it just leaked to everyone.
- A careful teacher takes a photocopy, writes on the photocopy, and hands it back. The register stays clean.
| At school | In JavaScript |
|---|---|
| The one class register everyone reads | shared data: the menu array, reachable from many places |
| Two teachers holding the same register | two variable names holding the same reference (address) to one array |
| Scribbling in the register | mutating the input: a side effect |
| Working on a photocopy | a pure function: it makes and returns new data |
| "Never write in the register" as a school rule | immutability: treat data as read only, make new versions instead |
The problem: the leaking Diwali offer
A restaurant menu has two dishes. diwaliOffer loops over the list and multiplies each price by 0.9 (10% off):
const menu = [
{ item: "Masala dosa", price: 80 },
{ item: "Filter coffee", price: 30 },
];
function diwaliOffer(list) {
for (const dish of list) dish.price = dish.price * 0.9;
return list;
}
console.log("Asha's bill:", diwaliOffer(menu));
console.log("Menu for the next customer:", menu);
Asha's bill: [
{ item: 'Masala dosa', price: 72 },
{ item: 'Filter coffee', price: 27 }
]
Menu for the next customer: [
{ item: 'Masala dosa', price: 72 },
{ item: 'Filter coffee', price: 27 }
]
Asha's bill is right. But the menu for the next customer also says 72 and 27. The real menu changed.
Why? Remember episode 8: an array or object is stored by reference. A reference is like the address of the data in memory; the variable holds the address, not a private copy. When we call diwaliOffer(menu), the parameter list receives the same address. So list and menu are two names for one array, and dish.price = ... changes the one and only menu. To mutate means to change data in place (instead of making a new version). When a function changes something outside itself (its input, a global variable, a file, the screen), that is called a side effect.
You can check this with ===, which for objects asks "same address?", not "same contents?": inside diwaliOffer, list === menu is true.
Pure functions
A pure function follows two rules:
- Same input, always the same output. It depends only on its parameters, never on hidden outside state.
- No side effects. It doesn't change its inputs or any variable outside it. It only reads its parameters and only gives back a return value, like
const add = (bill, price) => bill + price;.
Why bother? Pure functions are easy to test (give an input, check the output, episode 30), easy to reuse (they don't need any setup around them), and safe to call anywhere, in any order (they can't break anyone else's data).
Rule one breaking: hidden outside state
addToBill adds the price to a total that lives outside the function. We call it twice with the same 80. Then the pure add, also twice:
let total = 0;
function addToBill(price) {
total = total + price;
return total;
}
console.log(addToBill(80));
console.log(addToBill(80));
const add = (bill, price) => bill + price;
console.log(add(0, 80));
console.log(add(0, 80));
80
160
80
80
addToBill(80) gave 80, then 160, for the same input: its answer depends on the hidden total, and every call changes total (a side effect). add(0, 80) gave 80 and 80. Same input, same output, every time. Hidden state means surprises.
Other common impure things to watch for: reading Date.now() or Math.random() (different answer each call), changing a global variable, console.log (writing to the screen is a side effect too). A real program needs some side effects, of course (it must print and save something). The idea is to keep them at the edges and keep the calculations in the middle pure.
The fix: return new data with map + spread
Don't change the dishes, make new ones. list.map(...) returns a new array (episode 11). For each dish we build a new object: { ...dish } spreads (copies) item and price into it, and then price: ... overwrites the price with the discounted one:
const menu = [
{ item: "Masala dosa", price: 80 },
{ item: "Filter coffee", price: 30 },
];
function diwaliOffer(list) {
return list.map((dish) => ({ ...dish, price: dish.price * 0.9 }));
}
console.log("Asha's bill:", diwaliOffer(menu));
console.log("Menu for the next customer:", menu);
Asha's bill: [
{ item: 'Masala dosa', price: 72 },
{ item: 'Filter coffee', price: 27 }
]
Menu for the next customer: [
{ item: 'Masala dosa', price: 80 },
{ item: 'Filter coffee', price: 30 }
]
Asha gets 72 and 27; the menu stays 80 and 30. Notes:
- The arrow function returns an object literal, so it is wrapped in parentheses:
(dish) => ({ ... }). Without them,{would be read as the start of a function body. - Order matters inside
{ ...dish, price: ... }: later keys win, so the new price overwrites the copied one. - Treating data as read only and producing new versions instead of editing old ones is called immutability ("immutable" = cannot be changed). The rule of thumb: don't change, make new.
const is not immutability
"Just declare the menu with const, then it can't change." Let's test that:
const menu = [{ item: "Masala dosa", price: 80 }];
menu[0].price = 0;
menu.push({ item: "Free vada", price: 0 });
console.log(menu);
menu = [];
[ { item: 'Masala dosa', price: 0 }, { item: 'Free vada', price: 0 } ]
main.js:5
menu = [];
^
TypeError: Assignment to constant variable.
at Object.<anonymous> (main.js:5:6)
... (node:internal lines cut)
Node.js v24.22.2
Price 0 and a free vada, printed without complaint. The TypeError comes only on the last line, where we tried to point menu at a new array. const locks the name (the variable must always hold the same reference), not the data behind it. What's inside the array can still change freely.
Object.freeze: locking the data
Object.freeze(obj) makes an object's own properties read only: you can't change them, add new ones or delete them. It returns the same object, now frozen.
const dosa = Object.freeze({ item: "Masala dosa", price: 80, extras: { chutney: 2 } });
dosa.price = 0;
console.log(dosa.price);
80
The change was ignored. But silently: no error, nothing printed, which can hide bugs (you think you set the price, but you didn't).
Strict mode makes freeze shout
Strict mode is a stricter version of JavaScript that turns some silent mistakes into real errors. You switch it on by writing the string "use strict"; as the first line of the file (or of a function). We also try to change the chutney inside extras:
"use strict";
const dosa = Object.freeze({ item: "Masala dosa", price: 80, extras: { chutney: 2 } });
dosa.extras.chutney = 10;
console.log(dosa.extras);
dosa.price = 0;
{ chutney: 10 }
main.js:5
dosa.price = 0;
^
TypeError: Cannot assign to read only property 'price' of object '#<Object>'
at Object.<anonymous> (main.js:5:12)
... (node:internal lines cut)
Node.js v24.22.2
Two lessons:
- Chutney became 10. Freeze is shallow: it locks only the top level.
extrasis a separate object thatdosamerely holds a reference to, and that object is not frozen. - In strict mode, a frozen object shouts.
'#<Object>'is how V8 (the engine inside Node) names a plain object in error messages.
You don't always need to type "use strict": ES modules (import/export files, episode 18) and class bodies (episode 16) are strict automatically. We checked: the same frozen-price assignment in a .mjs file throws the same TypeError with no "use strict" line.
Checking with Object.isFrozen, and frozen arrays
Object.isFrozen(obj) tells you whether an object is frozen. On the frozen dosa, Object.isFrozen(dosa) is true but Object.isFrozen(dosa.extras) is false: the shallowness, confirmed. Outside strict mode, adding dosa.spicy = true and delete dosa.item are silently ignored too; the dosa still prints { item: 'Masala dosa', price: 80, extras: { chutney: 2 } }.
Arrays are objects, so they freeze too. On a frozen ["dosa", "idli"], menu[0] = "vada" is silently ignored, but menu.push("vada") throws even outside strict mode (built-in methods always behave strictly): TypeError: Cannot add property 2, object is not extensible. "Not extensible" means new properties can't be added.
A deep freeze helper
To freeze all the way down, freeze every nested object first, then the object itself. A function that calls itself like this is recursive:
"use strict";
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (typeof value === "object" && value !== null) deepFreeze(value);
}
return Object.freeze(obj);
}
const dosa = deepFreeze({ item: "Masala dosa", price: 80, extras: { chutney: 2 } });
console.log(Object.isFrozen(dosa.extras));
dosa.extras.chutney = 10;
true
main.js:10
dosa.extras.chutney = 10;
^
TypeError: Cannot assign to read only property 'chutney' of object '#<Object>'
at Object.<anonymous> (main.js:10:21)
... (node:internal lines cut)
Node.js v24.22.2
value !== null is needed because typeof null is "object" (an old JavaScript quirk). Use deep freeze for things that must never change, like a menu or app settings (config).
Copies: shallow vs deep
"Shallow" comes back with copies too. An order for table 4; copy is the order spread into a new object. We change the copy's table and push a vada into the copy's items:
const order = { table: 4, items: ["dosa", "coffee"] };
const copy = { ...order };
copy.table = 7;
copy.items.push("vada");
console.log("original:", order);
original: { table: 4, items: [ 'dosa', 'coffee', 'vada' ] }
The original kept table 4. But its items now include vada! Spread copies the top level only: table is a number, so the copy got its own 4; items is an array, so the copy got the same reference. copy.items and order.items are one array. That's a shallow copy: a new outer object whose nested objects are still shared. ([...arr], Object.assign({}, obj) and arr.slice() are shallow too.)
structuredClone: a deep copy
A deep copy copies nested arrays and objects as well, all the way down, so nothing is shared. structuredClone(value) is built into Node (17+) and modern browsers:
const order = { table: 4, items: ["dosa", "coffee"] };
const copy = { ...order };
copy.table = 7;
copy.items.push("vada");
console.log("original:", order);
const deep = structuredClone(order);
deep.items.push("idli");
console.log("original:", order);
console.log("deep copy:", deep);
original: { table: 4, items: [ 'dosa', 'coffee', 'vada' ] }
original: { table: 4, items: [ 'dosa', 'coffee', 'vada' ] }
deep copy: { table: 4, items: [ 'dosa', 'coffee', 'vada', 'idli' ] }
The original stays dosa, coffee, vada (the vada was pushed earlier through the shallow copy); only the deep copy has idli.
What structuredClone can and can't copy
It understands much more than JSON (episode 19). We cloned an order holding a Date, a Map and a Set (episode 21): structuredClone gave back a real, separate Date (instanceof Date is true, === the original is false), Map(1) { 'chutney' => 2 } and Set(2) { 'dosa', 'coffee' }. The old trick JSON.parse(JSON.stringify(x)) turned the date into the string '2026-11-01T19:30:00.000Z' and the Map and Set into empty objects {}.
But it cannot copy functions:
const order = { table: 4, total: () => 110 };
structuredClone(order);
node:internal/worker/js_transferable:127
const serializedData = nativeStructuredClone(value, idlOptions);
^
DOMException [DataCloneError]: () => 110 could not be cloned.
at new DOMException (node:internal/per_context/domexception:76:18)
at structuredClone (node:internal/worker/js_transferable:127:26)
at Object.<anonymous> (main.js:2:1)
... (node:internal lines cut)
Node.js v24.22.2
A DataCloneError is the error structuredClone throws for values it can't copy. And for class instances it copies the data but drops the class (the prototype, episode 17): cloning new Order(4) gives a plain { table: 4 }, copy instanceof Order is false, and its describe method is undefined.
So: structuredClone is perfect for plain data (objects, arrays, strings, numbers, dates, maps, sets). For objects with behaviour, copy them yourself (for example new Order(original.table)).
Safe sorting: sort mutates, toSorted doesn't
Some array methods change the array they're called on: push, pop, shift, unshift, splice, reverse, fill and sort. Watch sort:
const prices = [100, 25, 9, 250];
const sorted = prices.sort();
console.log("sorted:", sorted);
console.log("prices:", prices);
sorted: [ 100, 25, 250, 9 ]
prices: [ 100, 25, 250, 9 ]
Two surprises:
- It sorts as text. With no compare function,
sortturns each value into a string and compares them like words in a dictionary."100"starts with"1", which comes before"2"and"9". So 100, 25, 250, 9. - It sorts in place.
pricesitself changed, andsortedis just another name for the same array (sorted === pricesistrue).
Modern JavaScript (ES2023, Node 20+) adds copying versions that return a new array and leave the original alone:
const prices = [100, 25, 9, 250];
const sorted = prices.toSorted((a, b) => a - b);
console.log("sorted:", sorted);
console.log("prices:", prices);
console.log("reversed:", prices.toReversed());
console.log("with:", prices.with(0, 99));
sorted: [ 9, 25, 100, 250 ]
prices: [ 100, 25, 9, 250 ]
reversed: [ 250, 9, 25, 100 ]
with: [ 99, 25, 9, 250 ]
toSorted(compare): a sorted copy. The compare function(a, b) => a - breturns a negative number ifashould come first, positive ifbshould, 0 if equal. That makes it a number sort.toReversed(): a reversed copy.with(index, value): a copy with one position replaced. It's the immutable version ofprices[0] = 99.
More facts we checked on the same prices:
prices.toSorted()with no compare function still gives[ 100, 25, 250, 9 ]: the copying version fixes the mutation, not the text comparison.(a, b) => b - asorts highest first:[ 250, 100, 25, 9 ]. To sort menu objects, compare a property:menu.toSorted((a, b) => a.price - b.price).prices.with(-1, 199)counts from the end:[ 100, 25, 9, 199 ]. An index outside the array throwsRangeError: Invalid index : 10.
Mutating vs non-mutating array methods
On ["vada", "dosa", "idli", "upma"], toSpliced(1, 1, "pongal") gave [ 'vada', 'pongal', 'idli', 'upma' ] and left the array alone; splice(1, 1, "pongal") followed by reverse() changed the array itself to [ 'upma', 'idli', 'pongal', 'vada' ].
| Changes the original (mutating) | Returns a new array instead (non-mutating) |
|---|---|
arr.sort(fn) |
arr.toSorted(fn) |
arr.reverse() |
arr.toReversed() |
arr.splice(i, n, ...items) |
arr.toSpliced(i, n, ...items) |
arr[i] = value |
arr.with(i, value) |
arr.push(x) |
[...arr, x] or arr.concat(x) |
arr.unshift(x) |
[x, ...arr] |
arr.pop() / arr.shift() |
arr.slice(0, -1) / arr.slice(1) |
removing with splice |
arr.filter(...) |
obj.key = value |
{ ...obj, key: value } |
delete obj.key |
const { key, ...rest } = obj (use rest) |
map, filter, reduce, slice, concat, join, find, includes never change the array.
Immutable updates: add, change, remove without mutating
If you never change data, how does anything change? You make a new version every time. Three pure helpers cover almost every update to a list:
| Want to | Tool | Returns |
|---|---|---|
| add an item | spread: [...cart, newItem] |
a new array with the item at the end |
| change one item | map + spread: matching line becomes { ...line, qty } |
a new array; untouched lines are reused |
| remove an item | filter |
a new array without that item |
const cart = [{ item: "Masala dosa", qty: 1 }];
const addItem = (cart, item) => [...cart, { item, qty: 1 }];
const setQty = (cart, item, qty) => cart.map((line) => (line.item === item ? { ...line, qty } : line));
const removeItem = (cart, item) => cart.filter((line) => line.item !== item);
const cart2 = addItem(cart, "Filter coffee");
const cart3 = setQty(cart2, "Masala dosa", 2);
const cart4 = removeItem(cart3, "Filter coffee");
console.log("cart: ", cart);
console.log("cart3:", cart3);
console.log("cart4:", cart4);
cart: [ { item: 'Masala dosa', qty: 1 } ]
cart3: [ { item: 'Masala dosa', qty: 2 }, { item: 'Filter coffee', qty: 1 } ]
cart4: [ { item: 'Masala dosa', qty: 2 } ]
The original cart still has one dosa: every version still exists, so undo is just going back to the previous version. { item, qty: 1 } is shorthand for { item: item, qty: 1 }. This "new version for every change" style is exactly how React and other modern front-end libraries update their state (the data a screen shows).
Small steps snapped together: pipe
Picture a chai assembly line. Station 1 only boils water. Station 2 takes whatever came out of station 1 and adds milk. Station 3 adds sugar and hands the cup on. No station touches anything but the cup in front of it. Want ginger chai? Add one station. Each station is small, pure and easy to check on its own.
The stations: functions that make functions
A higher-order function is a function that takes a function as an argument, or returns a function, or both. You've used them since episode 11: map takes a function. discount and pipe below return one. Three small pure steps. addGst adds 5% GST (goods and services tax). round rounds to whole rupees. discount is a function that makes functions: give it 10, and it returns a new function that takes 10% off any price.
const discount = (percent) => (price) => price - (price * percent) / 100;
const addGst = (price) => price * 1.05;
const round = (price) => Math.round(price);
Running this alone prints nothing: it only defines the three stations. discount(10) remembers percent = 10 through a closure (episode 10). Taking a two-input function and feeding it one input now, the rest later, is called currying when it's written as one-argument-at-a-time functions like this, and partial application when you fix some arguments of an ordinary function (for example with bind). We checked: discount(10)(80) is 72, discount(20)(80) is 64, and with an ordinary priceWith(percent, price), priceWith.bind(null, 25) gives a function where festive(80) is 60.
The assembly line: pipe
pipe takes any number of steps (rest parameter ...steps, episode 12) and returns a function. Give that function a starting value, and reduce (episode 11) passes it through each step in order, feeding each step's result to the next:
const discount = (percent) => (price) => price - (price * percent) / 100;
const addGst = (price) => price * 1.05;
const round = (price) => Math.round(price);
const pipe = (...steps) => (start) => steps.reduce((value, step) => step(value), start);
const finalPrice = pipe(discount(10), addGst, round);
console.log(finalPrice(80));
console.log([80, 30, 120].map(finalPrice));
76
[ 76, 28, 113 ]
80 minus 10% is 72, plus GST is 75.6, rounded is 76. Mapped over a whole menu: 76, 28, 113. Combining small functions so the output of one becomes the input of the next is called function composition, and you just invented it.
compose, nesting, and tracing a pipe
pipe(f, g, h)(x) is the same as h(g(f(x))), but reads left to right like the assembly line. Its mirror image, compose, lists the steps right to left (the way nested calls are written) using reduceRight. A small debug step that logs and passes the value on lets you look inside the line:
const discount = (percent) => (price) => price - (price * percent) / 100;
const addGst = (price) => price * 1.05;
const round = (price) => Math.round(price);
const pipe = (...steps) => (start) => steps.reduce((value, step) => step(value), start);
const compose = (...steps) => (start) => steps.reduceRight((value, step) => step(value), start);
console.log(round(addGst(discount(10)(80))), compose(round, addGst, discount(10))(80));
const debug = (label) => (value) => {
console.log(label, value);
return value;
};
console.log(pipe(discount(10), debug("after discount"), addGst, debug("after GST"), round)(80));
76 76
after discount 72
after GST 75.60000000000001
76
- The nested calls and
composeboth give 76, likepipe. - The trace shows the real middle value is
75.60000000000001, not exactly 75.6: decimal money in floating point (episode 20). One more reason to keep aroundstation at the end.
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
dish.price = dish.price * 0.9 inside a function |
the shared menu changes for everyone (72, 27) | side effect on a shared reference | list.map((dish) => ({ ...dish, price: ... })) |
addToBill(80) twice |
80, then 160 | depends on hidden outside state | pass everything in: add(bill, price) |
const menu = [...]; menu = []; |
TypeError: Assignment to constant variable. |
const locks the name, not the data |
Object.freeze to lock the data |
const menu = [...]; menu[0].price = 0 |
works, no error | const doesn't freeze contents |
freeze, or make a new array |
frozen.price = 0 (no strict mode) |
silently ignored | sloppy mode hides the failure | "use strict"; or ES modules |
"use strict"; frozen.price = 0 |
TypeError: Cannot assign to read only property 'price' of object '#<Object>' |
the object is frozen | make a new object: { ...frozen, price: 0 } |
frozen.extras.chutney = 10 |
works: { chutney: 10 } |
freeze is shallow | deepFreeze |
Object.freeze(arr).push(x) |
TypeError: Cannot add property 2, object is not extensible |
frozen arrays can't grow | [...arr, x] |
const copy = { ...order }; copy.items.push("vada") |
the original's items get vada | spread is a shallow copy | structuredClone(order) |
structuredClone({ total: () => 110 }) |
DOMException [DataCloneError]: () => 110 could not be cloned. |
functions can't be cloned | clone only plain data |
prices.sort() |
[ 100, 25, 250, 9 ], and the original changed |
sorts as text, in place | prices.toSorted((a, b) => a - b) |
prices.with(10, 5) |
RangeError: Invalid index : 10 |
index outside the array | check the index (or -1 for last) |
Mini project: the immutable canteen bill
A frozen menu, carts that are never changed (every action returns a new cart), and bills built from pure steps with pipe:
"use strict";
const MENU = Object.freeze({ dosa: 80, coffee: 30, vada: 40 });
// Pure helpers: they only read their inputs and return new data
const addItem = (cart, key, qty = 1) => ({ ...cart, [key]: (cart[key] ?? 0) + qty });
const subtotal = (cart) => Object.entries(cart).reduce((sum, [key, qty]) => sum + MENU[key] * qty, 0);
const discount = (percent) => (price) => price - (price * percent) / 100;
const addGst = (price) => price * 1.05;
const round = (price) => Math.round(price);
const pipe = (...steps) => (start) => steps.reduce((value, step) => step(value), start);
const diwaliBill = pipe(subtotal, discount(10), addGst, round);
const normalBill = pipe(subtotal, addGst, round);
const empty = {};
const asha = addItem(addItem(addItem(empty, "dosa", 2), "coffee"), "vada");
const ravi = addItem(asha, "vada");
console.log("empty:", empty);
console.log("Asha:", asha, diwaliBill(asha), "with offer,", normalBill(asha), "without");
console.log("Ravi:", ravi, diwaliBill(ravi));
console.log("Asha's cart is still:", asha);
console.log(Object.entries(MENU).toSorted((a, b) => a[1] - b[1]).map(([k, p]) => `${k} ${p}`).join(" | "));
try {
MENU.dosa = 0;
} catch (err) {
console.log(err.name + ":", err.message);
}
empty: {}
Asha: { dosa: 2, coffee: 1, vada: 1 } 217 with offer, 242 without
Ravi: { dosa: 2, coffee: 1, vada: 2 } 255
Asha's cart is still: { dosa: 2, coffee: 1, vada: 1 }
coffee 30 | vada 40 | dosa 80
TypeError: Cannot assign to read only property 'dosa' of object '#<Object>'
addItembuilds a new object each time:[key]is a computed key (the key's name comes from a variable), andcart[key] ?? 0starts a new dish at 0.emptyis still{}, and Ravi's cart (Asha's plus one more vada) did not change Asha's.- Asha: 2×80 + 30 + 40 = 230 → minus 10% = 207 → plus GST = 217.35 → 217. Without the offer, 230 × 1.05 = 241.5 → 242. Ravi: 270 → 243 → 255.15 → 255.
- Changing the offer is just a different list of stations; nothing else changes.
toSortedlists the menu cheapest first without touchingMENU. - The menu is flat (no nested objects), so a plain
Object.freezeis enough; for nested menus usedeepFreeze. Freeze plus strict mode turns any accidental menu change into a loud error, whichtry/catch(episode 13) reports.
Practice
- Write a pure
addItem(cart, item)for an array cart that returns a new cart; prove the old cart is unchanged. - Freeze a shop config object in strict mode, try to change it, and read the error.
- Deep-copy an order that has a nested
customerobject and anitemsarray, change both in the copy, and print both. - Build
pipe(discount(20), addGst, round)and run it over[80, 30, 120].
Solutions
1.
const addItem = (cart, item) => [...cart, item];
const cart = ["dosa"];
const newCart = addItem(cart, "coffee");
console.log("old:", cart);
console.log("new:", newCart);
console.log(addItem(cart, "coffee"));
old: [ 'dosa' ]
new: [ 'dosa', 'coffee' ]
[ 'dosa', 'coffee' ]
Same input, same output (the third line), and no side effect on cart.
"use strict";on line 1, thenconst config = Object.freeze({ shopName: "Annapoorna Tiffins", gstPercent: 5 });andconfig.gstPercent = 0;.Object.isFrozen(config)printstrue, and the assignment stops the program withTypeError: Cannot assign to read only property 'gstPercent' of object '#<Object>'. Without"use strict"the change is silently ignored.
3.
const order = { table: 2, customer: { name: "Ravi" }, items: ["idli", "chai"] };
const copy = structuredClone(order);
copy.customer.name = "Meena";
copy.items.push("vada");
console.log("original:", order);
console.log("copy:", copy);
original: { table: 2, customer: { name: 'Ravi' }, items: [ 'idli', 'chai' ] }
copy: {
table: 2,
customer: { name: 'Meena' },
items: [ 'idli', 'chai', 'vada' ]
}
With { ...order } instead, the original would have become Meena with a vada.
4.
const discount = (percent) => (price) => price - (price * percent) / 100;
const addGst = (price) => price * 1.05;
const round = (price) => Math.round(price);
const pipe = (...steps) => (start) => steps.reduce((value, step) => step(value), start);
const festivePrice = pipe(discount(20), addGst, round);
console.log([80, 30, 120].map(festivePrice));
[ 67, 25, 101 ]
80 → 64 → 67.2 → 67; 30 → 24 → 25.2 → 25; 120 → 96 → 100.8 → 101.
Quick quiz
What does this print?
const a = { name: "Asha", tags: ["vip"] };
const b = { ...a };
b.name = "Ravi";
b.tags.push("new");
console.log(a.name, a.tags.length);
- A.
Asha 1 - B.
Asha 2 - C.
Ravi 2 - D.
Ravi 1
Answer
B (Asha 2). Real output:
Asha 2
Spread copies the top level, so b.name is b's own string and a.name stays "Asha". But tags is the same array in both objects, so the push is seen through a too: length 2. A shallow copy.
Interview questions
- What is a pure function? One that always returns the same output for the same input and has no side effects (doesn't change its inputs or anything outside it).
- What is a side effect? Give examples. Any change outside the function: mutating an argument, changing a global, logging, writing a file, a network call.
- Why prefer pure functions? Easy to test, reuse and reason about; safe to run in any order; no hidden coupling between parts of the program.
- Does
constmake an object immutable? No. It stops the variable being reassigned (Assignment to constant variable.); the object's contents can still change. - What does
Object.freezedo, and what are its limits? Makes own properties read only and blocks adding/deleting. It's shallow, and outside strict mode failed writes are silently ignored. - How do you deep-freeze an object? Recursively freeze every nested object, then the object itself.
- Shallow vs deep copy? Shallow: new outer object, nested objects shared (spread,
Object.assign,slice). Deep: everything copied (structuredClone). - What can't
structuredClonecopy? Functions (DataCloneError), DOM nodes; class instances lose their prototype and methods. - Why does
[100, 25, 9, 250].sort()give[100, 25, 250, 9]? The default sort compares values as strings. Pass(a, b) => a - b. - Difference between
sortandtoSorted?sortsorts in place and returns the same array;toSortedreturns a new sorted array and leaves the original alone. - What is a higher-order function? A function that takes or returns a function (
map,discount,pipe). - Write
pipe.const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);composeis the same withreduceRight. - Currying vs partial application? Currying: rewrite
f(a, b)asf(a)(b). Partial application: fix some arguments now (f.bind(null, a)), get a function for the rest.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Side effect | a function changing something outside itself | dish.price = ... on the shared menu |
| Reference | the "address" of an object or array; variables hold it, not a private copy | list and menu point at one array |
| Shared data | one object reachable through many names | the class register |
| Mutate | change data in place | menu.push(...), sort() |
| Pure function | same input → same output, no side effects | add(bill, price) |
| Impure function | depends on or changes outside state | addToBill with a global total |
| Hidden state | outside data a function secretly reads or changes | let total = 0 |
| Immutability | treating data as read only; making new versions instead of changing | map + spread |
| Immutable | cannot be changed | a frozen object |
Spread ... |
copy the items/keys of an array/object into a new one | { ...dish, price: 72 } |
const |
a variable that can't be reassigned (the name is locked, not the data) | const menu = [...] |
Object.freeze |
make an object's own properties read only (shallow) | Object.freeze(dosa) |
Object.isFrozen |
check whether an object is frozen | Object.isFrozen(dosa.extras) → false |
| Shallow | affects only the top level, not nested objects | freeze, spread |
| Deep freeze | freeze every nested object too | deepFreeze(MENU) |
| Recursive function | a function that calls itself | deepFreeze |
| Extensible | new properties can still be added | frozen arrays are not |
| Strict mode | stricter JavaScript that turns silent mistakes into errors | "use strict"; |
| Read-only property | a property that can't be assigned | frozen price |
| Shallow copy | new outer object, nested objects still shared | { ...order } |
| Deep copy | a copy of everything, all the way down; nothing shared | structuredClone(order) |
structuredClone |
built-in deep copy for plain data, dates, maps, sets | structuredClone(order) |
DataCloneError |
the error structuredClone throws for uncloneable values |
a function inside |
| In place | changing the original instead of returning a copy | sort, reverse, splice |
| Compare function | tells sort/toSorted the order of two items |
(a, b) => a - b |
toSorted / toReversed / toSpliced / with |
copying versions of sort / reverse / splice / arr[i] = v |
prices.with(0, 99) |
| Higher-order function | takes and/or returns a function | map, discount, pipe |
| A function that makes functions | a function that returns a new, configured function | discount(10) |
| Closure | a function remembering variables from where it was made | discount(10) remembers 10 |
| Currying | writing f(a, b) as f(a)(b), one argument at a time |
discount(10)(80) |
| Partial application | fixing some arguments now, the rest later | priceWith.bind(null, 25) |
| Function composition | joining functions so each output feeds the next input | round(addGst(discount(10)(80))) |
pipe |
compose steps left to right (in reading order) | pipe(discount(10), addGst, round) |
compose |
compose steps right to left (nested-call order) | compose(round, addGst, discount(10)) |
reduce / reduceRight |
fold an array into one value from the left / right | inside pipe / compose |
| Rest parameter | gathers any number of arguments into an array | (...steps) |
| GST | goods and services tax, 5% on restaurant food here | price * 1.05 |
TypeError |
an operation not allowed on that kind of value | assigning a frozen property |
RangeError |
a number outside the allowed range | prices.with(10, 5) |
Summary
- A function that changes shared data creates side effects: silent bugs, like a Diwali offer that changes the menu for everyone. Objects and arrays are shared by reference.
- A pure function: same input, same output, no side effects. Return new data (
map+ spread) instead of changing the old: immutability. constlocks the name, not the data.Object.freezelocks the data, silently outside strict mode, with aTypeErrorin strict mode, and only at the top level (use a deep freeze for nested data).- Spread is a shallow copy: nested arrays and objects are still shared.
structuredClonecopies all the way down (but not functions, and class instances lose their methods). sortmutates and sorts as text. UsetoSorted((a, b) => a - b),toReversed,toSplicedandwithfor new arrays.- Small pure steps (
discount(10),addGst,round) snap together withpipe: that's function composition.
Next episode: Testing with node:test. Pure functions are the easiest code in the world to test, so you'll stop checking console.log by eye and let the computer check your code for you.