Memoization, async deduplication, fluent method chaining, lazy evaluation — these patterns underpin React.memo, Lodash, RxJS, and every performant frontend system. This guide builds deep understanding with diagrams, annotated implementations, and 8 interactive problems.
Functional patterns are the invisible backbone of modern JavaScript. You use them constantly — often without realising it. Understanding them at the implementation level separates senior engineers from mid-level ones.
Where these patterns appear
Memoization — eliminate redundant computation. The backbone of React.memo, useMemo, useCallback, reselect, and every selector library.
Method chaining — expressive, readable APIs. jQuery, Lodash, RxJS, query builders, and virtually every data-transformation library use this pattern.
Lazy evaluation — defer work until needed. Critical for performance with large datasets, infinite sequences, and pipelines that short-circuit early.
Async deduplication — prevent redundant network requests by sharing in-flight Promises. Used in SWR, React Query, and every production data-fetching layer.
Key Insight
These patterns appear in every mid-to-senior frontend interview. Interviewers ask you to implement memoize, build a fluent API, or explain lazy evaluation because they reveal whether you think about performance, API design, and correctness — not just whether you can write working code.
1. Memoization
Memoization caches the return value of a function keyed on its arguments. Repeated calls with the same arguments skip the computation and return the cached result in O(1) — turning expensive functions into near-instant lookups.
MemoizeMemoize: cache hit vs miss flow showing input args serialized to key, checked in Map, hit returns cached value, miss calls function and stores result
Basic implementation
The cache is a Map from serialized arguments to return value. On each call, check the cache first. On a miss, compute the result, store it, and return it.
example.js
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
// Usage
const expensiveFn = memoize((n) => {
console.log("computing...");
return n * n;
});
expensiveFn(5); // "computing..." → 25
expensiveFn(5); // (no log) → 25 ← cache hit
expensiveFn(6); // "computing..." → 36
The JSON.stringify limitation
JSON.stringify works for primitive arguments but fails silently for functions, circular references, undefined, Symbol, and class instances. For those cases, provide a custom key function:
example.js
// Custom key function for object arguments
const memoizeWithKey = (fn, { keyFn } = {}) => {
const cache = new Map();
return function(...args) {
const key = keyFn ? keyFn(args) : JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
};
// Use object's id as key instead of stringifying the whole object
const memoizedFetch = memoizeWithKey(fetchUser, {
keyFn: ([user]) => user.id,
});
Warning
Never memoize side-effectful functions (ones that write to a DB, update DOM, trigger events) or non-deterministic functions like Math.random() or Date.now(). Memoization assumes the same inputs always produce the same output — a contract these functions violate by definition.
Practice it: Implement memoize from scratch. Pay attention to how this is preserved with fn.apply(this, args).
Basic memoization grows unbounded. In production systems you need to control cache size and lifetime to prevent memory leaks and stale data. The three canonical eviction strategies are LRU, TTL, and LFU.
Cache PolicyCache eviction policies: LRU evicts least recently used, TTL evicts expired entries, LFU evicts least frequently used
Memoize Cache Size GrowthCache growth comparison: unbounded cache grows linearly, LRU caps at capacity, TTL bounds with time expiry
Deep equality key for object arguments
When arguments are objects, JSON.stringify produces different keys for semantically equal inputs with different key ordering ({a:1,b:2} vs {b:2,a:1}). Deep-equal comparison solves this but requires iterating all cached keys — an O(n) lookup per call. Reserve it for functions called infrequently with complex arguments.
LRU eviction with Map (insertion order)
JavaScript's Map preserves insertion order. Deleting and re-inserting an entry on access moves it to the end (most recent). The front of the map is always the least-recently-used entry — evict it when capacity is exceeded.
example.js
function memoizeLRU(fn, capacity = 100) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
const val = cache.get(key);
cache.delete(key); // remove from current position
cache.set(key, val); // re-insert at end (most recent)
return val;
}
const result = fn.apply(this, args);
cache.set(key, result);
if (cache.size > capacity) {
// The first key in Map iteration order is the oldest
cache.delete(cache.keys().next().value);
}
return result;
};
}
Combine LRU + TTL for production use: cap the cache size AND expire stale entries. SWR and React Query use this exact combination — a bounded LRU with a stale-while-revalidate TTL that keeps the old value while fetching fresh data in the background.
Practice it: Implement advanced memoize handling object arguments and LRU eviction.
Basic memoize breaks for async functions: if the same key is called twice before the first Promise resolves, both calls trigger separate network requests. The fix is to cache the Promise itself — not the resolved value.
The in-flight problem
example.js
// NAIVE — broken for concurrent calls
const memoizedFetch = memoize(fetchUser); // basic memoize
// Called concurrently before either resolves:
memoizedFetch(42); // cache miss → fires request #1
memoizedFetch(42); // cache miss (Promise not resolved yet) → fires request #2
// Two identical network requests! Basic memoize stores the resolved value,
// but it hasn't resolved yet when the second call checks the cache.
Fix: cache the Promise, not the resolved value
Store the Promise in the cache before it resolves. All concurrent callers with the same key receive the same Promise object and attach their own .then() handlers — they all resolve together when the single request completes.
example.js
function memoizeAsync(fn) {
const cache = new Map();
return async function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const promise = fn.apply(this, args).then(
(result) => {
// Replace the pending promise with a resolved one
cache.set(key, Promise.resolve(result));
return result;
},
(err) => {
cache.delete(key); // don't cache errors — allow retry
throw err;
},
);
cache.set(key, promise); // cache IMMEDIATELY — before it resolves
return promise;
};
}
// Now concurrent calls share one request:
memoizedFetch(42); // cache miss → fires ONE request, caches the Promise
memoizedFetch(42); // cache HIT → returns the same pending Promise
memoizedFetch(42); // cache HIT → same Promise, resolves with same value
Error handling strategy
On rejection, the cache entry is deleted. This ensures the next call retries instead of permanently returning a rejected Promise. Optionally, implement a retry backoff or mark the entry as failed for a short TTL to avoid hammering a failing endpoint.
Note
This is exactly how SWR, React Query, and fetchdeduplication work internally. When multiple components call useQuery("user/42") simultaneously, the library fires one request and shares the Promise across all subscribers.
Practice it: Build async memoize with in-flight deduplication from scratch.
A fluent interface is an API where each method returns this — the same object — enabling calls to be chained together without intermediate variable assignments. The result is code that reads like a sentence.
Method Chaining FlowMethod chaining flow: each method returns this, enabling a chain of select, where, limit, sort calls on the same object, terminated by execute
Builder PatternQueryBuilder state machine: each chained method call adds configuration until build produces the final SQL
The builder pattern
The canonical method chaining use case is the builder pattern: accumulate configuration through a chain of method calls, then execute or build the final result with a terminal method.
example.js
class QueryBuilder {
#table = "";
#conditions = [];
#fields = ["*"];
#limitVal = null;
#sortField = null;
from(table) { this.#table = table; return this; }
select(...fields) { this.#fields = fields; return this; }
where(condition) { this.#conditions.push(condition); return this; }
limit(n) { this.#limitVal = n; return this; }
sort(field) { this.#sortField = field; return this; }
build() {
let query = `SELECT ${this.#fields.join(", ")} FROM ${this.#table}`;
if (this.#conditions.length) {
query += ` WHERE ${this.#conditions.join(" AND ")}`;
}
if (this.#sortField) query += ` ORDER BY ${this.#sortField}`;
if (this.#limitVal) query += ` LIMIT ${this.#limitVal}`;
return query;
}
}
// Reads like an English sentence:
new QueryBuilder()
.from("users")
.select("name", "email")
.where("age > 18")
.where("active = true")
.sort("name")
.limit(10)
.build();
// → "SELECT name, email FROM users WHERE age > 18 AND active = true ORDER BY name LIMIT 10"
Private fields with # vs closures
Using #privateField (ES2022 private class fields) prevents external mutation of builder state — users cannot bypass the API by directly setting builder.table = "injected". An alternative is a closure-based approach (factory function returning an object) where state variables are never exposed as properties.
Key Insight
jQuery's entire API is a fluent interface — $("div").addClass("active").css("color","red").fadeIn(). Lodash's _.chain() creates a wrapped value that enables chaining. RxJS operators are chainable via .pipe(). The pattern is everywhere because it produces the most readable transformation code.
Practice it: Design a fluent interface for a utility class — each method should return this to enable chaining.
Advanced chaining patterns add execution order control and async support to the basic fluent interface. These appear in middleware systems, plugin architectures, and animation pipelines.
Priority-based execution ordering
Instead of executing methods in registration order, each method call carries a priority weight. When the chain is resolved, steps are sorted by priority before execution — lower numbers run first (like CSS z-index, but inverted).
An async chain stores a list of async functions and resolves them sequentially — the output of each step becomes the input of the next. This is a manual implementation of Promise chaining and mirrors how Express middleware works.
example.js
class AsyncChain {
#steps = [];
then(fn) { this.#steps.push(fn); return this; }
async execute(initialValue) {
let result = initialValue;
for (const fn of this.#steps) {
result = await fn(result); // sequential — each step waits for the previous
}
return result;
}
}
// Usage:
const pipeline = new AsyncChain()
.then(async (id) => fetchUser(id)) // step 1: fetch
.then(async (user) => enrichUser(user)) // step 2: enrich
.then(async (user) => sendWelcomeEmail(user)); // step 3: notify
await pipeline.execute(userId);
Note
The difference between sequential and parallel async chaining is whether you use for...of + await (sequential) or Promise.all() (parallel). Sequential is correct when each step depends on the previous result. Parallel is correct when steps are independent and you want to minimise total latency.
Eager evaluation processes all items at each step. Lazy evaluation stores operations as a list of transforms and applies them all together in a single pass when a terminal method requests the value — enabling short-circuit optimisation and eliminating intermediate arrays.
Lazy EvalEager vs lazy evaluation: eager processes all items immediately creating intermediate arrays, lazy stores transforms and applies them only on terminal call, short-circuiting early
Eager vs lazy: the performance gap
For array.filter(...).map(...).find(...), the eager path creates two intermediate arrays and processes every element at each step. For an array of 1,000 items where the matching element is near the start, lazy evaluation can stop after processing ~50 items — a 20x reduction in work.
Lazy sequence implementation
example.js
class LazySequence {
#source;
#ops = [];
constructor(source) { this.#source = source; }
filter(fn) { this.#ops.push({ type: "filter", fn }); return this; }
map(fn) { this.#ops.push({ type: "map", fn }); return this; }
// Terminal method — triggers execution
value() {
const result = [];
outer: for (const item of this.#source) {
let current = item;
for (const op of this.#ops) {
if (op.type === "filter" && !op.fn(current)) continue outer;
if (op.type === "map") current = op.fn(current);
}
result.push(current);
}
return result;
}
// Short-circuit terminal — stops at first match
find(fn) {
for (const item of this.#source) {
let current = item;
let pass = true;
for (const op of this.#ops) {
if (op.type === "filter" && !op.fn(current)) { pass = false; break; }
if (op.type === "map") current = op.fn(current);
}
if (pass && fn(current)) return current;
}
return undefined;
}
}
// Usage — no intermediate arrays, single pass:
const result = new LazySequence([1, 2, 3, ..., 1000])
.filter((x) => x % 2 === 0)
.map((x) => x * x)
.find((x) => x > 100); // → 144 (12²), stops after processing ~12 items
Generator-based lazy sequences
JavaScript generators (function*) are the language's built-in lazy evaluation mechanism. Each yield pauses execution until the consumer requests the next value — no intermediate arrays, infinite sequences possible.
example.js
function* lazyFilter(iterable, fn) {
for (const item of iterable) {
if (fn(item)) yield item;
}
}
function* lazyMap(iterable, fn) {
for (const item of iterable) {
yield fn(item);
}
}
// Compose: filter then map, zero intermediate arrays:
const pipeline = lazyMap(
lazyFilter([1, 2, 3, 4, 5, 6], (x) => x % 2 === 0),
(x) => x * x,
);
for (const val of pipeline) console.log(val); // 4, 16, 36
Tip
Array iterator protocol (for...of) works with any iterable — including generators, Sets, Maps, and custom objects with a [Symbol.iterator]() method. Building LazySequence as an iterable lets it compose with the entire standard library.
Infinite sequences with generators
Generators can represent infinite sequences — they never terminate, but eachyield pauses until the next value is consumed. This is impossible with arrays (which must be finite in memory) but trivial with lazy evaluation.
example.js
function* naturals() {
let n = 0;
while (true) yield n++;
}
// Consumer controls how many values to take:
const gen = lazyMap(
lazyFilter(naturals(), (x) => x % 2 === 0),
(x) => x * x,
);
console.log(gen.next().value); // 0 (0²)
console.log(gen.next().value); // 4 (2²)
console.log(gen.next().value); // 16 (4²)
// The generator keeps running; we take only what we need.
Transducers — advanced composability
Transducers are composable higher-order reducers. They decouple the transformation logic from the data source and the terminal operation — the same transducer can process arrays, streams, observables, or async iterables. Libraries like Ramda and RxJS use this pattern extensively for building reusable transformation pipelines.
example.js
// A transducer wraps a reducer (step function) with a transform
const map = (fn) => (step) => (acc, val) => step(acc, fn(val));
const filter = (pred) => (step) => (acc, val) =>
pred(val) ? step(acc, val) : acc;
// Compose transducers — no intermediate arrays
const compose = (...fns) => (x) => fns.reduceRight((v, fn) => fn(v), x);
const xform = compose(
filter((x) => x % 2 === 0),
map((x) => x * x),
);
// Apply to any source
const result = [1, 2, 3, 4, 5]
.reduce(xform((acc, v) => [...acc, v]), []);
// → [4, 16] — single pass, no intermediate arrays
// Same transducer works on streams, observables, or async iterables
The key insight: transducers describe what to compute without specifyingwhere or when. The same composed transducer works on an array, an Observable, a Node stream, or an async generator — you just provide the terminal reducer (step function).
Before diving into specific patterns, it's essential to understand the foundational concepts that underpin all functional programming. These principles are what make patterns like memoization, method chaining, and lazy evaluation work.
Pure Functions
A pure function always produces the same output for the same input and has no side effects. It does not modify external state, read from the filesystem, or log to the console. This property — determinism — is what makes memoization safe: if a function is pure, you can cache its results knowing the output will never change for the same inputs.
example.js
// Pure — safe to memoize
const add = (a, b) => a + b;
// Impure — violates referential transparency
let counter = 0;
const impureAdd = (a, b) => { counter++; return a + b; };
Immutability
Immutability means data never changes in place — operations return new values instead. This enables time-travel debugging, undo/redo, and confident state management. React's setState, Redux reducers, and Zustand stores all rely on immutability for predictable state transitions.
example.js
// Mutable — changes in place (dangerous)
const user = { name: "Alice" };
user.name = "Bob"; // mutates original
// Immutable — returns new value
const updateName = (user, newName) => ({ ...user, name: newName });
// Original { name: "Alice" } is preserved
Higher-Order Functions
Functions that take other functions as arguments or return them as results.Array.map, Array.filter, and Function.prototype.bind are all higher-order. The memoize utility itself is a higher-order function — it takes a function and returns a wrapped version with caching behaviour.
Referential Transparency
An expression is referentially transparent if it can be replaced by its value without changing the program's behaviour. This is the property that enables lazy evaluation and reactive programming — the system can defer or reorder computations because the result is always the same regardless of when it runs.
Functors & Monads — a visual primer
Functors and monads are container types that wrap a value with additional context — optionality (Maybe), error handling (Either), or asynchrony (Promise). The key insight is that they let you transform values inside the container without unwrapping it manually.
Functor MonadFunctor vs Monad: Functor has map that transforms value inside context, Monad adds flatMap that prevents nested contexts
A Functor implements map: given a value in a box and a transformation function, it applies the function inside the box. A Monad adds flatMap (also called bind or chain): it lets you apply a function that itself returns a boxed value, without producing a nested box.Promise.then is flatMap — that's why you get a flat Promise back instead of a Promise of Promise of value.
Interview Cheat Sheet
These 8 questions cover the full range of functional pattern questions asked in frontend interviews at every level.
1What is memoization and when should you NOT use it?
Memoization caches a function's return value keyed on its arguments. Do NOT memoize side-effectful functions (DB writes, DOM mutations), non-deterministic functions (Math.random, Date.now), or functions whose result should change over time — memoize assumes same-in → same-out.
2How do you handle object arguments in memoize?
JSON.stringify produces different keys for {a:1,b:2} vs {b:2,a:1}. Provide a custom keyFn that normalises the key (e.g. sort keys before stringifying, or use the object's unique id). For deep equality, iterate cached keys and compare — O(n) but correct.
3What is in-flight deduplication and why does it matter?
When multiple async calls with the same key fire before any resolves, naive memoize misses the cache (the Promise hasn't resolved yet) and sends duplicate requests. Deduplication caches the pending Promise immediately, so all concurrent callers receive the same Promise and fire only one network request.
4How does async memoize cache the Promise instead of the result?
Call cache.set(key, promise) before awaiting the result. Subsequent callers with the same key hit the cache and get the same pending Promise. Once resolved, replace it with a resolved Promise. On rejection, delete the cache entry to allow retry.
5What makes an API 'fluent'?
Every method returns this (the same object), enabling calls to be chained: obj.step1().step2().step3(). The chain accumulates configuration or transforms state, and a final terminal method (build, execute, value) produces the result.
6What is lazy evaluation and when is it more efficient than eager?
Lazy evaluation stores operations as a list of transforms and applies them only when a terminal method is called. It is more efficient when: (1) a short-circuit terminal like find can stop early, (2) intermediate arrays waste memory, or (3) you pipeline large datasets and only need a subset of results.
7What is the difference between method chaining and the builder pattern?
Method chaining is the mechanism (each method returns this). The builder pattern is a design pattern that uses method chaining to construct a complex object — accumulate configuration with chained calls, produce the object with a terminal call like build() or create(). All builders use chaining; not all chaining is a builder.
8How does React.memo relate to memoize?
React.memo is memoize applied to a component render: it caches the rendered output keyed on props. If props are shallowly equal on re-render, React skips re-rendering and returns the cached output. useMemo and useCallback are memoize applied to values and functions within a component — keyed on the dependency array.
Key Takeaways
1.Memoization converts expensive function calls into O(1) cache lookups — the same mechanism behind React.memo, useMemo, and reselect.
2.JSON.stringify is a reliable cache key for primitive arguments but silently produces wrong keys for objects with different key ordering. Use a custom keyFn for object arguments.
3.LRU eviction uses Map insertion order: delete + re-insert on access to move entries to the 'most recent' end. Evict the first key (oldest) when at capacity.
4.Async memoize must cache the Promise before it resolves — not the resolved value. This is the only way to deduplicate concurrent calls with the same key.
5.On async error, always delete the cache entry. Caching a rejected Promise permanently breaks all future callers with that key.
6.Fluent interfaces return this from every method, enabling a chain of calls that reads like a sentence. The builder pattern is the canonical use case.
7.Lazy evaluation stores operations as a transform list and applies them in a single pass on terminal call. The key benefit is short-circuit: find or first can stop processing as soon as the condition is met.
8.JavaScript generators are the language's built-in lazy evaluation — each yield pauses execution until the consumer requests the next value. They support infinite sequences and zero-allocation pipelines.
9.Priority-based chaining sorts registered steps by priority before execution, enabling declarative control over operation order in plugin architectures and middleware pipelines.
10.These six patterns — memoize, LRU/TTL cache, async dedup, method chaining, lazy evaluation, and async pipelines — form the toolkit for every high-performance, expressive JavaScript API.