Functional Programming Questions
Functional programming as a paradigm and a way of structuring code: pure functions and side-effect isolation (a pure core with effects at the edges, and how effects are described versus run), immutability and persistent data structures with structural sharing, updating nested immutable data including lenses, higher-order functions, function composition, currying and partial application, folds and recursion over data (including tail recursion), algebraic data types and pattern matching, total functions and Maybe/Either style error values, functors, applicatives and monads as patterns for composing effects and threading state, parser combinators as a worked example, lazy evaluation and lazy or streaming pipelines, and property-based testing of pure code. Covers reasoning about programs as composed transformations rather than mutable state, in a dedicated functional language such as Haskell or Scala, or in a multi-paradigm language such as JavaScript, TypeScript, Kotlin or Python. Boundary: closures and the this binding as language mechanics, the event loop and reactive streams, threads and STM-style concurrency, performance profiling, and exception or resource handling are covered elsewhere.
You have a function that increments a counter held in a global or an IORef-style mutable cell. Refactor it so the state is passed through explicitly and returned, for example with a State monad or a reducer. Show how to run it from a given initial value, and explain what you gained.
Sample Answer
Direct answer
Replace the hidden variable with a function whose inputs and outputs are the whole story: it takes the current state and returns a pair, the result and the new state (state => [result, newState]). Nothing is read from or written to anything outside. To run it, you supply the starting value yourself: the first call gets the initial state, and each later call gets the state the previous call returned. A State monad is just a convenient way to chain these functions so you do not pass the state by hand (a monad here means a type of computation that comes with a chain operation: run one step, feed its result to the next step); a reducer (state, action) => newState is the same idea specialised to "one function that handles every change", and it is what React's useReducer expects. What you gain: calls are repeatable (same state in gives the same answer out), tests need no setup or teardown of globals, and you can see every state transition.
The refactor in four steps
import assert from "node:assert/strict";
// Before: hidden mutable state
let counter = 0;
const nextImpure = () => ++counter;
console.log("impure:", nextImpure(), nextImpure(), "(depends on a hidden global)");
// After 1: state in, [result, new state] out. Nothing outside is read or written.
const next = (n) => [n + 1, n + 1]; // [value to hand out, new state]
const [a, s1] = next(0);
const [b, s2] = next(s1);
console.log("explicit state:", a, b, "final state:", s2);
// After 2: reducer, the same idea React uses: (state, action) => newState
const reducer = (state, action) => {
switch (action.type) {
case "increment": return { count: state.count + 1 };
case "add": return { count: state.count + action.by };
default: return state; // unknown action: same reference back
}
};
const run = (init, actions) => actions.reduce(reducer, init);
console.log("reducer from 10:", run({ count: 10 }, [{ type: "increment" }, { type: "add", by: 5 }]));
assert.deepEqual(run({ count: 0 }, []), { count: 0 });
const start = { count: 3 };
assert.equal(reducer(start, { type: "noop" }), start); // unchanged state keeps identity
assert.deepEqual(start, { count: 3 }); // unchanged
// A real change: new object, input left alone (a frozen input makes any mutation throw in strict mode)
const frozen = Object.freeze({ count: 3 });
const changed = reducer(frozen, { type: "increment" });
assert.notEqual(changed, frozen); // new object per change
assert.deepEqual(changed, { count: 4 });
assert.deepEqual(frozen, { count: 3 }); // input never mutated
// After 3: a tiny State monad: a "stateful computation" is a function s => [a, s]
const State = {
of: (a) => (s) => [a, s],
chain: (m, f) => (s) => { const [a, s2] = m(s); return f(a)(s2); },
get: (s) => [s, s],
put: (s2) => () => [undefined, s2],
};
const tick = State.chain(State.get, (n) => State.chain(State.put(n + 1), () => State.of(n)));
const threeTicks = State.chain(tick, (x) =>
State.chain(tick, (y) => State.chain(tick, (z) => State.of([x, y, z]))));
const runState = (m, init) => m(init); // "run it from a given initial value"
console.log("runState(threeTicks, 100):", runState(threeTicks, 100));
console.log("runState(threeTicks, 0): ", runState(threeTicks, 0));
// Effectful variant: StateT over async. The step is s => Promise<[a, s]>.
const tickIO = async (n) => { await Promise.resolve(); console.log(" logging tick", n); return [n, n + 1]; };
const [first, afterOne] = await tickIO(7);
const [second, afterTwo] = await tickIO(afterOne);
console.log("effectful:", first, second, afterTwo);
// The decision logic stays pure and is tested without any I/O:
const decide = (n) => (n >= 2 ? [false, n] : [true, n + 1]);
assert.deepEqual(decide(1), [true, 2]);
assert.deepEqual(decide(2), [false, 2]);
console.log("pure decide() tested with no I/O");
Output (Node 22, one run of exactly this file):
impure: 1 2 (depends on a hidden global)
explicit state: 1 2 final state: 2
reducer from 10: { count: 16 }
runState(threeTicks, 100): [ [ 100, 101, 102 ], 103 ]
runState(threeTicks, 0): [ [ 0, 1, 2 ], 3 ]
logging tick 7
logging tick 8
effectful: 7 8 9
pure decide() tested with no I/O
- Impure counter.
nextImpurereads and writes the module-levelcounter. Its result depends on how many times anyone, anywhere, called it before. - Explicit state.
next(n)returns[n + 1, n + 1](the value handed out and the new state). The caller threadss1into the next call. Passing0always gives1, with a final state of2after two calls. - Reducer.
reducer(state, action)returns a new object per change, hands back the same object for an unknown action, and never mutates its input. The assertions check all three: the unknown-action case keeps identity, and theincrementcase runs on a frozen object, so a reducer that didstate.count++; return state;would throw (or, unfrozen, hand back the same object) and fail the file. Running it from an initial value is a fold:actions.reduce(reducer, init), which gives{ count: 16 }from10afterincrementandadd 5. - State monad. A stateful computation is a function
s => [a, s]. Two pieces of the helper look alike but differ:State.getis already a computation (a function from a statesto[s, s], which reads the state without changing it), whileState.putis a function that takes the new value and then returns a computation() => [undefined, s2]that ignores the old state and installs the new one, which is why the code writesState.put(n + 1)with a call.State.chain(m, f)runsm, feeds its result tof, and passes the state along, sothreeTicksreads like a sequence of steps but remains a pure function of its starting value.runState(threeTicks, 100)returns[[100, 101, 102], 103]: the three results and the final state. Starting from0gives[[0, 1, 2], 3]. Traced by hand fortickrun with state 100:State.getturns state 100 into the pair[100, 100], sonis 100;State.put(101)replaces the state with 101 and returns nothing useful (undefined);State.of(100)then returns the savednas the result, leaving the state at 101. Sotickrun on 100 gives[100, 101].threeTicksrunstickon 100, then on 101 (giving[101, 102]), then on 102 (giving[102, 103]), and collects the three results[100, 101, 102]with the last state, 103.
How this is the reducer idea in frontend work
React's useReducer(reducer, initialArg) returns [state, dispatch]; the reducer takes (state, action) and returns the next state, and React documents that it must be pure. Two documented consequences matter: if the reducer returns a value identical to the current state (compared with Object.is, the built-in "are these exactly the same value" check, which for objects means the same reference), React skips re-rendering, and in Strict Mode (a development-only checking mode) React calls your reducer twice to expose impure code. A reducer that mutates and returns the same object (state.count++; return state;) is therefore both a stale-UI bug and a double-increment bug in development. The same shape powers Redux (a popular JavaScript state-container library) and event-sourced systems (systems that store the list of events and derive the current state from it): the current state is a fold over the history of actions, so you can replay, log or undo.
The effectful variant: state plus I/O
Real programs also need to log, call the network or read the clock while threading state. Keep the layers separate: the effectful step has type s => Promise<[a, s]> (in Haskell, StateT Int IO: StateT is the "state transformer" that adds a state of type Int on top of an underlying computation, here IO, Haskell's type for computations that talk to the outside world; an IORef is Haskell's mutable cell, the thing this refactor removes). tickIO above awaits something, logs, and returns [n, n + 1]; the caller threads the state exactly as before. The part you want to test, the decision logic (decide), stays pure: decide(1) and decide(2) are asserted with plain inputs and outputs, no mocks, no I/O. The rule of thumb: effects at the edges, decisions in pure functions, and the state threaded explicitly between them.
The Haskell version of step 4 and the effectful variant (run with runghc, using the mtl library, a standard Haskell package that provides State and StateT). Syntax to know: tick :: State Int Int says tick is a stateful computation whose state is an Int and whose result is an Int; the do block runs steps in order; n <- get reads the state into n; put sets it; return n produces the result; replicateM 3 tick repeats a computation three times and collects the results in a list; lift lifts an IO action into the stacked computation; >> means "run this, discard its result, then run the next"; runState m s and runStateT m s run the computation from initial state s:
import Control.Monad (replicateM)
import Control.Monad.State
tick :: State Int Int
tick = do
n <- get
put (n + 1)
return n
threeTicks :: State Int [Int]
threeTicks = replicateM 3 tick
tickIO :: StateT Int IO Int
tickIO = do
n <- get
lift (putStrLn ("logging tick " ++ show n))
put (n + 1)
return n
main :: IO ()
main = do
print (runState threeTicks 100)
r <- runStateT (tickIO >> tickIO) 7
print r
print (take 3 (filter even [1 ..]) :: [Int])
Output:
([100,101,102],103)
logging tick 7
logging tick 8
(8,9)
[2,4,6]
runState threeTicks 100 gives the same ([100,101,102],103) as the JavaScript, and runStateT (tickIO >> tickIO) 7 prints both log lines and returns (8,9): the last result and the final state.
What you gain, and when not to bother
| Gain | Why |
|---|---|
| Testability | Call with a state, assert on [result, newState]; no global reset between tests |
| Replay and debugging | A list of actions plus an initial state reproduces any state |
| Concurrency safety | No shared variable to race on; each caller owns its state value |
| Change detection | A new object means "changed", the same object means "unchanged" (what Object.is checks in React) |
Do not thread state by hand through a deep call chain for its own sake. In a UI, useReducer or a store already does the threading. In a hot loop where copying state per step is costly, local mutation inside a function that still looks pure from outside is a fair trade.
Pitfalls
- Forgetting to return the new state (returning only the result) silently drops updates.
- Using the old state after calling a step is a stale-state bug: always thread the latest
s. - A "pure" reducer that calls
Date.now()orMath.random()is not pure; pass those in through the action.
Without using the built-in map, implement map for a list or array by hand. Then explain how it composes with filter and reduce in a pipeline, and one downside of your hand-rolled version compared with the library one.
Sample Answer
Direct answer
map(arr, fn) returns a new array of the same length where each element is fn applied to the matching element of the input; the input is not changed. The hand-rolled version is a loop that allocates the result and fills it. map, filter and reduce compose into a pipeline: filter chooses which elements survive, map transforms them, reduce collapses them to one value, and each step takes the previous step's array as input. The hand-rolled version differs from the built-in in details such as sparse arrays, thisArg and the generic array-like behaviour, and every stage that returns an array (filter and map, but not a final reduce to a single value) builds an intermediate array.
Implementation, pipeline and the differences
// Naive: one loop, new array, calls fn on every index 0..length-1
function myMap(arr, fn) {
const out = new Array(arr.length);
for (let i = 0; i < arr.length; i++) out[i] = fn(arr[i], i, arr);
return out;
}
// Closer to the spec: skip holes, keep them in the result
function myMapSparse(arr, fn) {
const out = new Array(arr.length);
for (let i = 0; i < arr.length; i++) if (i in arr) out[i] = fn(arr[i], i, arr);
return out;
}
const myFilter = (arr, p) => { const out = []; for (let i = 0; i < arr.length; i++) if (p(arr[i], i, arr)) out.push(arr[i]); return out; };
const myReduce = (arr, f, init) => { let acc = init; for (let i = 0; i < arr.length; i++) acc = f(acc, arr[i], i, arr); return acc; };
console.log(myMap([1, 2, 3], (x) => x * 2));
console.log(myMap(["a", "b"], (s, i) => s + i));
const calls = [];
myMap([1, , 3], (x) => (calls.push(x), x)); // hand-rolled visits the hole
const callsB = [];
[1, , 3].map((x) => (callsB.push(x), x)); // built-in does not
console.log("naive visited:", calls, "| built-in visited:", callsB);
console.log("naive result :", myMap([1, , 3], (x) => x * 2), "| built-in:", [1, , 3].map((x) => x * 2));
const sp = myMapSparse([1, , 3], (x) => x * 2);
console.log("sparse-aware:", sp, "| has hole at 1:", !(1 in sp));
console.log("parseInt pitfall:", ["1", "2", "3"].map(parseInt), "fixed:", myMap(["1", "2", "3"], (s) => parseInt(s, 10)));
// Pipeline: sum of squares of the even numbers
const nums = [1, 2, 3, 4, 5, 6];
const result = myReduce(myMap(myFilter(nums, (n) => n % 2 === 0), (n) => n * n), (a, b) => a + b, 0);
console.log("pipeline (hand-rolled):", result, "| built-in:", nums.filter((n) => n % 2 === 0).map((n) => n * n).reduce((a, b) => a + b, 0));
// Each stage allocates a new array: count allocations
let allocs = 0;
const filt = (a, p) => (allocs++, myFilter(a, p));
const mp = (a, f) => (allocs++, myMap(a, f));
mp(filt(nums, (n) => n % 2 === 0), (n) => n * n);
console.log("intermediate arrays built by filter->map:", allocs);
// Single pass fused with reduce
console.log("single pass reduce:", myReduce(nums, (acc, n) => (n % 2 === 0 ? acc + n * n : acc), 0));
In the callbacks (x) => (calls.push(x), x), the comma operator evaluates its operands left to right and returns the last one: calls.push(x) records the element that was visited, and then x is returned as the mapped value, so the callback both logs and passes the value through.
Run in a node:22 container it prints:
[ 2, 4, 6 ]
[ 'a0', 'b1' ]
naive visited: [ 1, undefined, 3 ] | built-in visited: [ 1, 3 ]
naive result : [ 2, NaN, 6 ] | built-in: [ 2, <1 empty item>, 6 ]
sparse-aware: [ 2, <1 empty item>, 6 ] | has hole at 1: true
parseInt pitfall: [ 1, NaN, NaN ] fixed: [ 1, 2, 3 ]
pipeline (hand-rolled): 56 | built-in: 56
intermediate arrays built by filter->map: 2
single pass reduce: 56
Design choices
- The callback receives
(element, index, array), the same three arguments as the built-in, so callers can use the index. That is also the source of the classic bug on theparseInt pitfallline:["1","2","3"].map(parseInt)returns[1, NaN, NaN]becauseparseInttakes a second parameter (the radix, or number base) andmappasses the index there. MDN documents this exact behaviour; the fixes are(s) => parseInt(s, 10)orNumber. - The input is never written to, so
myMapis pure as long asfnis. Writing to a localoutarray is invisible to callers. - Complexity: O(n) time and O(n) extra space for the result. No edge case is special: an empty input gives an empty array, and an input of length 1 gives length 1.
Composing with filter and reduce
filter keeps elements for which a predicate returns true and reduce folds the remaining ones into one value, so "sum of squares of the even numbers" in the example reads left to right as filter (2, 4, 6), map (4, 16, 36), reduce (4 + 16 + 36 = 56). Every stage is a function from array to value, so stages can be swapped, reordered or tested separately. Order matters: filtering first means map squares 3 elements, not 6.
One downside of the hand-rolled version
The most visible one is sparse arrays (arrays with empty slots, as in [1, , 3]). The built-in map does not call the callback for an empty slot and keeps the hole in the result (MDN), but the naive loop visits index 1, hands undefined to the callback, and returns NaN there. The i in arr check in myMapSparse restores the built-in behaviour. Other differences: the built-in accepts an optional second argument, thisArg, which becomes this inside a regular (non-arrow) callback, and myMap has no such parameter. The built-in is also generic over array-like inputs, meaning objects that are not arrays but have a length and integer keys, such as { length: 3, 0: "a", 1: "b", 2: "c" }; Array.prototype.map.call(thatObject, fn) works on them (MDN), while myMap needs an array. In a Node 22 run, Array.prototype.map.call({ length: 3, 0: "a", 1: "b", 2: "c" }, (s) => s.toUpperCase()) gives [ 'A', 'B', 'C' ] and [1, 2].map(function (x) { return x * this.k; }, { k: 10 }) gives [ 10, 20 ].
A downside shared by the built-in and by any chain of them is the intermediate arrays: filter(...).map(...) builds two arrays (the "intermediate arrays" line shows 2 for the two-stage chain), where a single reduce pass or a plain loop builds none besides the result. For arrays of thousands of items this is irrelevant; for very large arrays or hot paths, fuse the stages in one loop, or use a lazy iterator pipeline, where each stage hands one element at a time to the next instead of building a whole array. With generator functions (functions that yield values on demand):
function* gFilter(it, p) { for (const x of it) if (p(x)) yield x; }
function* gMap(it, f) { for (const x of it) yield f(x); }
const nums = [1, 2, 3, 4, 5, 6];
const seen = [];
const lazy = gMap(
gFilter(nums, (n) => { seen.push("filter " + n); return n % 2 === 0; }),
(n) => { seen.push("map " + n); return n * n; });
let sum = 0;
for (const v of lazy) sum += v;
console.log(sum);
console.log(seen.join(", "));
Run in a node:22 container it prints:
56
filter 1, filter 2, map 2, filter 3, filter 4, map 4, filter 5, filter 6, map 6
The order shows the stages interleaving element by element (filter 2 is followed at once by map 2), and no intermediate array is ever built. Recursive versions ([f(head), ...map(tail)]) are an elegant alternative but cost a stack frame per element and copy on every spread, so a loop is the right tool in JavaScript.
Haskell contrast
Haskell's map f (x:xs) = f x : map f xs is the recursive form, and lazy evaluation means the result is produced element by element, so map and filter chains over a big list do not build full intermediate lists in memory when consumed incrementally.
What is a pure function, and what does immutability buy you? Take one small piece of code that mutates shared state and show how you would rewrite it as pure functions over immutable data. Where does that change help with testing, reasoning about the code, and running it concurrently, and where does it cost you?
Sample Answer
Direct answer
A pure function returns a result that depends only on its arguments and does nothing observable besides returning it: no reading or writing of outside variables, no I/O, no clock, no randomness. Call it twice with the same arguments and you get the same value. Immutability means a value is never changed after it is created; an "update" builds a new value and leaves the old one intact. Together they let you reason about a function by reading it alone, test it with plain inputs and outputs, and share its data across concurrent tasks without locks. The cost is allocation (copying: building a fresh value on every update) and some friction where the problem is naturally about changing state.
Rewrite: mutating shared state to pure functions
The impure version changes a shared cart object. The pure version takes the old cart and returns a new one.
// Impure: mutates a shared cart object
const cart = { items: [], total: 0 };
function addItemImpure(name, price) {
cart.items.push(name);
cart.total += price;
}
// Pure: same inputs always give the same output, nothing outside is touched
const addItem = (cart, name, price) => ({
items: [...cart.items, name],
total: cart.total + price,
});
// Testing
addItemImpure("pen", 2);
addItemImpure("pen", 2);
console.log("impure after 2 calls:", JSON.stringify(cart));
const empty = Object.freeze({ items: Object.freeze([]), total: 0 });
const c1 = addItem(empty, "pen", 2);
const c2 = addItem(c1, "book", 10);
console.log("pure c1:", JSON.stringify(c1));
console.log("pure c2:", JSON.stringify(c2));
console.log("empty untouched:", JSON.stringify(empty), "| same input twice equal:",
JSON.stringify(addItem(empty, "pen", 2)) === JSON.stringify(addItem(empty, "pen", 2)));
// Frozen input makes a hidden mutation fail loudly (push throws on a frozen array in any mode)
try { empty.items.push("x"); } catch (e) { console.log("frozen push ->", e.constructor.name); }
// Concurrency: read-modify-write across an await loses updates on shared state
let shared = 0;
async function bump() { const v = shared; await null; shared = v + 1; }
await Promise.all([bump(), bump(), bump()]);
console.log("shared mutable counter after 3 concurrent bumps:", shared);
// Immutable: every task computes from its own value, then results are combined
const bumpPure = async (v) => { await null; return v + 1; };
const results = await Promise.all([0, 0, 0].map(bumpPure));
console.log("pure results:", results, "sum of increments:", results.reduce((a, b) => a + b, 0));
// Cost: a copy per update is O(n)
let big = Object.freeze({ items: [], total: 0 });
let copies = 0;
for (let i = 0; i < 1000; i++) { copies += big.items.length; big = addItem(big, "x", 1); }
console.log("elements copied across 1000 appends:", copies);
Run as an ES module in a node:22 container (Node 22), it prints:
impure after 2 calls: {"items":["pen","pen"],"total":4}
pure c1: {"items":["pen"],"total":2}
pure c2: {"items":["pen","book"],"total":12}
empty untouched: {"items":[],"total":0} | same input twice equal: true
frozen push -> TypeError
shared mutable counter after 3 concurrent bumps: 1
pure results: [ 1, 1, 1 ] sum of increments: 3
elements copied across 1000 appends: 499500
Notes on the choices:
- The impure
addItemImpurehas no way to be called "again from a clean slate": the second call sees the first call's leftovers.addItem(empty, ...)can be called any number of times from the sameempty. Object.freezeis shallow (it freezes the object it is given, not objects nested inside it), so the example freezes theitemsarray too. Freezing is a safety net that turns an accidental mutation into aTypeError: methods such aspushthrow in any mode, while a plain assignment such ascart.total = 5throws only in strict mode (ES modules are always strict) and is silently ignored in sloppy-mode scripts. In TypeScript,readonlyandReadonlyArray<T>give the same protection at compile time at no runtime cost.
Where it helps
| Concern | Impure and shared | Pure and immutable |
|---|---|---|
| Testing | Arrange global state, call, inspect the global, reset it | Call with an input, compare the returned value. No setup, no teardown, no mocks for the logic itself |
| Reasoning | Any function that can reach cart might have changed it; you must read all of them | The result of addItem(c1, ...) is determined by what is written at the call site; c1 is still valid afterwards, which also makes undo, history and "previous vs next" comparison trivial |
| Concurrency | Two tasks interleave their read and write steps and an update is lost | Nothing is shared and writable, so there is nothing to lock |
The concurrency row is the output above. The three bump() calls each read shared as 0 before any of them writes, so the final value is 1, not 3. A data race is two threads touching the same memory at once with at least one writing, so the result depends on timing. JavaScript has no data race in that thread sense, but any read-modify-write that spans an await has the same lost-update shape. The pure bumpPure takes its input as an argument, returns a new value, and the caller combines the three results, so nothing can be overwritten. With real threads (Kotlin, Java, Scala) the argument is stronger: data that nobody can modify can be read from many threads without locks.
A second payoff is for UI code: React's useState and Redux reducers compare old and new state by reference (prev === next). A pure update that returns a new object when something changed, and the same object when nothing did, makes "did it change?" a one-pointer comparison.
Where it costs
- Copying. Each
addItemcopies the array: the last line of the output shows 499,500 element copies for 1,000 appends (0 + 1 + ... + 999), so building a list by repeated copy is quadratic. (Big-O notation describes how work grows with the size n of the input: O(n) means work proportional to n, so copying a 1,000-item array costs about 1,000 steps; O(log n) means work grows only with the number of times you can halve n, so about 10 steps for 1,000 items.) Persistent data structures are collections that keep every old version usable after an update by sharing the unchanged parts between the old and new version instead of copying them. They are balanced or tree-shaped, so one update copies one path from the root, about O(log n) rather than O(n). Haskell'sData.Mapis the standard example in Haskell, Immutable.js is a JavaScript library of such collections, and Immer is a library that lets you write ordinary-looking mutations on a draft copy and reuses every untouched branch of a plain JS object when it produces the new one. If you only remember one tool for a React/Redux app, Immer is the usual choice. In small, user-sized collections the copy is irrelevant; in a hot loop over millions of elements, a local mutation is the right call. - Allocation pressure. More short-lived objects means more work for the garbage collector (the runtime component that finds objects nothing references any more and frees their memory).
- Awkward fits. Genuinely stateful things (a canvas, a socket, a running counter shared by users) do not become pure by wishing; the pure part is the decision about what to do, and the effect is performed at the boundary.
- Local mutation is fine. A function that builds an array with
pushinside and returns it is still pure from the outside, because no caller can observe the mutation. Purity is a property of the interface, not of every line.
Same idea in Haskell
In Haskell values are immutable and functions are pure by default: addItem :: Cart -> String -> Int -> Cart cannot touch the outside world, and the type says so. Impurity must appear in the type (IO). JavaScript and TypeScript do not enforce any of this, so purity there is a discipline backed by freezing, readonly and code review.
You have a deeply nested settings object that must be updated immutably, for example changing one field three levels down while sharing the rest. Show how to do it by hand. Then explain what a lens (getter/setter pair) is and how composing lenses makes this reusable, and when it is overkill.
Sample Answer
Direct answer
To change one field three levels down without mutating anything, copy every object on the path from the root to that field (with spread, { ...obj, key: newValue }) and reuse every object off the path by reference. That is structural sharing: the new root is a different object, but billing and any sibling branch are the very same objects as before, so === still says "unchanged" for them. A lens is a small value that bundles a getter and a setter for one place in a structure ({ get, set }); lenses compose, so a lens for user, one for prefs, one for notifications and one for push combine into a single lens for user.prefs.notifications.push that you build once and reuse. It is worth it when the same deep paths are updated from many places; it is overkill for one or two updates, where the spread is clearer.
By hand, then with a lens, then as a path API
import assert from "node:assert/strict";
const settings = {
user: { name: "Ada", prefs: { theme: "light", notifications: { email: true, push: false } } },
billing: { plan: "pro" },
};
// 1. By hand: spread every level on the path, reuse everything off the path
const byHand = {
...settings,
user: {
...settings.user,
prefs: {
...settings.user.prefs,
notifications: { ...settings.user.prefs.notifications, push: true },
},
},
};
assert.equal(settings.user.prefs.notifications.push, false); // original untouched
assert.equal(byHand.user.prefs.notifications.push, true);
assert.equal(byHand.billing, settings.billing); // shared, same reference
assert.equal(byHand.user.prefs.theme, settings.user.prefs.theme);
assert.notEqual(byHand.user, settings.user); // path nodes are new
console.log("by hand: billing shared =", byHand.billing === settings.billing);
// 2. A lens is a getter/setter pair for one place in a structure
const lens = (get, set) => ({ get, set });
const prop = (key) => lens((o) => o[key], (o, v) => (Object.is(o[key], v) ? o : { ...o, [key]: v }));
// compose(outer, inner): focus on outer first, then inside it
const compose = (outer, inner) =>
lens((o) => inner.get(outer.get(o)), (o, v) => outer.set(o, inner.set(outer.get(o), v)));
const over = (l, f, o) => l.set(o, f(l.get(o)));
const pushLens = ["user", "prefs", "notifications", "push"].map(prop).reduce(compose);
console.log("get:", pushLens.get(settings));
const viaLens = pushLens.set(settings, true);
assert.deepEqual(viaLens, byHand);
assert.equal(viaLens.billing, settings.billing);
console.log("lens set equals by-hand:", JSON.stringify(viaLens) === JSON.stringify(byHand));
console.log("over (toggle):", over(pushLens, (b) => !b, settings).user.prefs.notifications.push);
// setting the same value returns the SAME object (no pointless new identity)
assert.equal(pushLens.set(settings, false), settings);
// 3. Path-based API with type validation on set and reference identity for untouched branches
const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function setIn(obj, path, value, check) {
if (path.length === 0) return value;
const [key, ...rest] = path;
if (FORBIDDEN.has(key)) throw new Error(`illegal path segment: ${key}`);
if (!isPlain(obj) || !Object.hasOwn(obj, key)) throw new Error(`no such path: ${path.join(".")}`);
if (rest.length === 0 && check && !check(value, obj[key])) {
throw new TypeError(`type mismatch at ${key}: expected ${typeof obj[key]}, got ${typeof value}`);
}
const child = setIn(obj[key], rest, value, check);
return child === obj[key] ? obj : { ...obj, [key]: child };
}
const sameType = (next, prev) => typeof next === typeof prev;
const out = setIn(settings, ["user", "prefs", "theme"], "dark", sameType);
console.log("theme:", out.user.prefs.theme, "| billing shared:", out.billing === settings.billing,
"| notifications shared:", out.user.prefs.notifications === settings.user.prefs.notifications);
assert.equal(setIn(settings, ["user", "prefs", "theme"], "light", sameType), settings);
for (const [path, v] of [[["user", "prefs", "theme"], 5], [["user", "nope"], 1], [["__proto__", "polluted"], true]]) {
try { setIn(settings, path, v, sameType); console.log("NOT REJECTED", path); }
catch (e) { console.log("rejected:", e.constructor.name, "-", e.message); }
}
assert.equal({}.polluted, undefined);
// The guard itself must be what rejects it: pin the message, and cover an OWN "__proto__" key
assert.throws(() => setIn(settings, ["__proto__", "polluted"], true, sameType), /illegal path segment/);
const parsed = JSON.parse('{"__proto__": {"x": 1}}'); // JSON.parse creates an OWN "__proto__" key
assert.equal(Object.hasOwn(parsed, "__proto__"), true);
assert.throws(() => setIn(parsed, ["__proto__", "x"], 2), /illegal path segment/);
Output (Node 22, one run of exactly this file; every assert in the file passes, so nothing else is printed):
by hand: billing shared = true
get: false
lens set equals by-hand: true
over (toggle): true
theme: dark | billing shared: true | notifications shared: true
rejected: TypeError - type mismatch at theme: expected string, got number
rejected: Error - no such path: nope
rejected: Error - illegal path segment: __proto__
What each part is doing
By hand. Object spread makes a shallow copy, which means it copies the top level only and the nested objects stay shared (MDN's spread page states this). That is exactly what you want off the path and exactly what you must override on the path, which is why you spread at every level you walk through. The asserts show the original push is still false, the copy's is true, and billing is the same object (reused, not copied). The theme assert only shows the value survived: it is a string, so it would be equal even in a deep copy; the object-valued billing is what proves sharing. Cost: O(depth) object allocations plus the width of each copied level, not the size of the whole tree.
Lens. prop("user") is a lens for one key. compose(outer, inner) gets by getting through both and sets by setting the inner value into the outer's current value and then setting the outer. Worked on the example, take outer as the lens for user.prefs.notifications and inner as the lens for push. Get: outer.get(settings) is { email: true, push: false }, and inner.get of that is false. Set to true: first read the outer's current value, { email: true, push: false }; then inner.set on it gives a new object { email: true, push: true } (the email field is untouched); then outer.set(settings, thatNewObject) puts it back, and because outer is itself a composition, it does the same trick one level up through prefs and user. Each level contributes one fresh copy and every field off the path is reused. Reducing the four props gives pushLens, whose get returns false, and whose set(settings, true) produces the same tree as the hand-written version (checked by assert.deepEqual) while keeping billing shared. over(lens, f, obj) is "get, transform, set" in one call, used here to toggle. The setter returns the same object when the value is unchanged (Object.is check, the built-in test for "exactly the same value"), so a no-op update keeps identity and a UI memoisation (caching a result and reusing it while the input reference is unchanged, as React.memo does) does not re-render.
Path-based API with validation. Use this form when the path arrives as data (a list of keys from a config file or a form field) instead of being fixed in code. setIn(obj, ["user", "prefs", "theme"], "dark", sameType) does the same walk with a path array:
- It returns a new root where only the three path objects are new. The output line shows
billingandnotificationsare the same references as in the original. - Setting the value it already has returns the original object (asserted).
- Validation on set: writing the number
5tothemethrowsTypeErrorbecausesameTypecomparestypeofthe new value with the existing one. A missing key (user.nope) throws, so typos do not create fields. - Safety: the path segments
__proto__,constructorandprototypeare rejected. A path API built from untrusted strings (config files, URLs, JSON) is otherwise a route to prototype pollution, where an attacker writes toObject.prototypeand changes behaviour of every object.{}.pollutedstaysundefined.Object.hasOwnis used for the existence check so inherited names liketoStringare not treated as fields, and on an ordinary object literal that check alone already refuses__proto__(it is inherited, not own). The explicit list is what protects an object built byJSON.parse, which can create an own"__proto__"key thathasOwnaccepts; the final asserts require theillegal path segmentmessage for both cases, so deleting theFORBIDDENcheck makes the file fail. This path builder copies with spread rather than assigning through the path, so it is defence in depth here, and the same segments must be blocked in any variant that mutates in place.
When a lens is overkill
| Situation | Use |
|---|---|
| One or two updates, depth 2 to 3 | Spread by hand |
| Many call sites updating the same deep path, or paths chosen at runtime | A lens or a path helper |
| Large state with lots of arrays and many edits in one handler | An Immer-style draft (the Immer library hands your function a temporary copy to mutate with ordinary assignments, then returns a new immutable object with only the changed parts copied) |
| Very large collections where copying a level per edit is too slow | A persistent data structure library (collections designed so that each update returns a new version that shares most of its memory with the old one) |
A hand-rolled lens is about ten lines, but it does not handle arrays or optional fields; a library for lenses earns its place only when you need that. The TypeScript wrinkle is that a typed path API (setIn(obj, ["user", "prefs", "theme"], v) where the compiler checks the path and the value type) needs advanced TypeScript features (template-literal types that build string types such as "user.prefs.theme", and tuple types that fix the length and element types of the path array) and is much more work than the runtime code above. Often a single typed setter per hot path is the pragmatic answer.
Pitfalls
Object.freezeis shallow, so freezing the root does not protect nested objects.- Arrays on the path need
[...arr.slice(0, i), newItem, ...arr.slice(i + 1)]orarr.map(...), not a key spread. - Spread copies own enumerable properties only, so class instances lose their prototype and non-enumerable fields.
- Spreading a level you did not need to change (for example
{ ...settings.billing }) breaks reference identity for no reason and defeats memoisation.
Your team is debating whether a small UI widget that keeps a counter and re-renders a view should be written with classes and mutable fields or as plain functions over immutable state. Sketch both versions in JavaScript or TypeScript, then tell me which you would ship and what you would give up by choosing it.
Sample Answer
Direct answer
I would ship the functional version: state is an immutable value, a pure reducer (a function (state, action) => newState) is the only code that decides what the next state is, a view function turns state into output, and a few lines of mutable shell connect it to the page. I would give up a little brevity and some in-place speed, and I would keep a class only for the parts that own a resource (a socket, a timer, a canvas). Run on the same steps, the two versions show the difference in testability and in how exposed the state is.
Both versions
// ---------- Version A: class with mutable fields ----------
class CounterWidget {
private count = 0;
history: number[] = [];
constructor(private root: { text: string }) {}
increment(): void {
this.history.push(this.count);
this.count += 1;
this.render();
}
undo(): void {
const prev = this.history.pop();
if (prev !== undefined) this.count = prev;
this.render();
}
private render(): void {
this.root.text = `Count: ${this.count}`;
}
}
// ---------- Version B: plain functions over immutable state ----------
type State = { readonly count: number; readonly history: readonly number[] };
type Action = { type: "increment" } | { type: "undo" };
const initial: State = { count: 0, history: [] };
const reduce = (s: State, a: Action): State => {
switch (a.type) {
case "increment":
return { count: s.count + 1, history: [...s.history, s.count] };
case "undo": {
if (s.history.length === 0) return s;
return { count: s.history[s.history.length - 1], history: s.history.slice(0, -1) };
}
}
};
const view = (s: State): string => `Count: ${s.count}`;
// the thin imperative shell: the only place with mutation and effects
const mount = (root: { text: string }) => {
let state = initial;
const dispatch = (a: Action) => {
const next = reduce(state, a);
if (next === state) return; // nothing changed, skip the re-render
state = next;
root.text = view(state);
};
root.text = view(state);
return dispatch;
};
// ---------- Checks ----------
let failures = 0;
const eq = (label: string, got: unknown, want: unknown) => {
const ok = JSON.stringify(got) === JSON.stringify(want);
if (!ok) failures++;
console.log((ok ? "pass " : "FAIL ") + label + ": " + JSON.stringify(got));
};
// B needs no widget, no root, no setup: input state and action, output state
const s1 = reduce(initial, { type: "increment" });
const s2 = reduce(s1, { type: "increment" });
eq("B reduce twice", s2, { count: 2, history: [0, 1] });
eq("B old state untouched", s1, { count: 1, history: [0] });
eq("B undo on empty returns same object", reduce(initial, { type: "undo" }) === initial, true);
eq("B view", view(s2), "Count: 2");
const rootB = { text: "" };
const dispatch = mount(rootB);
dispatch({ type: "increment" });
dispatch({ type: "increment" });
dispatch({ type: "undo" });
eq("B mounted", rootB.text, "Count: 1");
// The skip-render guard in dispatch: count how often the view is written
let writes = 0;
const rootC = { get text() { return ""; }, set text(_v: string) { writes++; } };
const dispatchC = mount(rootC); // initial render: 1 write
dispatchC({ type: "undo" }); // reducer returns the same state: no write
dispatchC({ type: "increment" }); // new state: 1 write
eq("B skips the render when nothing changed", writes, 2);
// A needs a root object and drives it through methods
const rootA = { text: "" };
const w = new CounterWidget(rootA);
w.increment();
w.increment();
w.undo();
eq("A mounted", rootA.text, "Count: 1");
// the cost of exposed mutable state: any holder of `history` can corrupt the widget
const leaked = w.history;
leaked.push(999);
w.undo();
eq("A after outside code pushed to history", rootA.text, "Count: 999");
if (failures > 0) throw new Error(failures + " checks failed");
Compiled and run (TypeScript 5, node:22 container):
npx -y -p typescript@5 tsc --strict --target es2022 --module commonjs --outDir out counter.ts
node out/counter.js
pass B reduce twice: {"count":2,"history":[0,1]}
pass B old state untouched: {"count":1,"history":[0]}
pass B undo on empty returns same object: true
pass B view: "Count: 2"
pass B mounted: "Count: 1"
pass B skips the render when nothing changed: 2
pass A mounted: "Count: 1"
pass A after outside code pushed to history: "Count: 999"
The eq helper counts every mismatch and the last line of the file throws if any were counted. The checks at the end are both a test and the argument. Two of them guard the claims made below: deleting the if (s.history.length === 0) return s; line makes the undo-on-empty check print FAIL, and deleting the if (next === state) return; line in dispatch makes the render-count check print FAIL (3 writes instead of 2).
The trade-offs, against the code
- Testability.
reducetakes a value and returns a value: the fourBchecks need no widget, no root element and no setup, and each one sets its own input. The class needs arootto be constructed and is driven by calling methods in order, so a test reads as a story rather than an assertion, and tests that share an instance can leak into each other. - Mutability. The class keeps
historyas a public array so the demo can show the hazard: the last check pushes999into it from outside and the nextundo()sets the count to 999. Makinghistoryprivate closes that hole, but the underlying issue stays: any method can change state in place, so you must read every method to know what can happen. In version B,reduce(s1, ...)leavess1untouched (the "old state untouched" check), so undo, time travel (stepping the app backward and forward through earlier states, which is possible because every past state is still intact) and "did anything change?" (next === state) come for free. - Composition. Reducers combine by calling each other on slices of state; views combine as ordinary function calls. Class widgets combine by holding references to each other, which tends to spread state across objects.
- Maintainability. Version B puts every state change in one
switch, which is the place to look when a bug report says "the count is wrong". The cost is that adding a feature means adding an action type and a case, more lines thanthis.count += 1. - What you give up. (1) Ceremony: actions, a union type, a dispatch shell. (2) Allocation: every update creates a new state object. For a counter this is nothing; for large state updated thousands of times per second it can matter, and you would then use structural sharing (the new state reuses every unchanged part of the old one by reference and copies only the path that changed) or Immer (a library that lets you write ordinary mutating code against a temporary draft and returns a new immutable state with structural sharing). (3)
readonlyin TypeScript is a compile-time promise only, not enforced at runtime, so a strayas anycan still mutate. (4) Teammates who think in objects need a short ramp.
They blend in practice
The functional core is exactly what frameworks ask of you. React's useReducer takes the same (state, action) function, and its documentation says the reducer must be pure and must not mutate state: if you return the same object, React skips re-rendering, which is the same next === state check the shell does above. A hook-based component is a function over state, and a class is still the right tool for a thing with identity and a lifecycle, such as a Web Component (a custom HTML tag you define yourself, for example <my-counter>, by writing a class that extends the browser's built-in HTMLElement base class, which the browser instantiates and then notifies when it is attached to or removed from the page). The decision is "where does the state change logic live", not "classes or functions everywhere".
What would flip the choice
Choose the class if the widget owns a resource with setup and teardown, if the codebase and its tests are already object-oriented and consistency is worth more, or if profiling shows allocation per update is a measured cost. For a counter and a view with history, B is smaller to reason about and easier to test.
Unlock Full Question Bank
Get access to all 7 Functional Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.