Sub topic 2
Working Without Mutation
This chapter assumes you know arrow functions, spread syntax, and what a pure function is. It covers four connected tools: immutable updates, higher-order functions, array transformations, and composition.
Updating Without Changing
Mutation means changing an existing object or array in place. Shared data that mutates causes bugs that are hard to trace, because any code holding a reference sees the change. The fix is to build a new value instead.
const user = { name: 'Ada', tags: ['math'] };
const renamed = { ...user, name: 'Grace' };
const tagged = { ...user, tags: [...user.tags, 'code'] };
const nums = [3, 1, 2];
const sorted = nums.toSorted((a, b) => a - b); // ES2023, Node 20+
console.log(user.name, user.tags.length); // Ada 1
console.log(renamed.name, tagged.tags); // Grace [ 'math', 'code' ]
console.log(nums, sorted); // [ 3, 1, 2 ] [ 1, 2, 3 ]Higher-Order Functions
A higher-order function either takes a function as an argument or returns one. Because the behavior comes in as a parameter, one function can handle the shared "how" while the caller supplies the "what."
map, filter, and reduce
These array methods are higher-order functions that return new values and leave the original array alone:
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 60, paid: true }
];
const revenue = orders
.filter((o) => o.paid)
.map((o) => o.total)
.reduce((sum, t) => sum + t, 0);
console.log(revenue); // 100Always pass an initial value to reduce. If you leave it out, calling reduce on an empty array throws a TypeError.
pipe and compose
Composition builds one function out of several smaller ones. pipe applies the functions left to right, and compose applies them right to left.
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const trim = (s) => s.trim();
const toUpper = (s) => s.toUpperCase();
const exclaim = (s) => `${s}!`;
console.log(pipe(trim, toUpper, exclaim)(' hi ')); // HI!
console.log(compose(exclaim, toUpper, trim)(' hi ')); // HI!Exercise
Using pipe, write a function that takes the orders array above and returns the number of unpaid orders, without mutating the array.
Show answer
const countUnpaid = pipe((xs) => xs.filter((o) => !o.paid), (xs) => xs.length); countUnpaid(orders) returns 1.