Functional Patterns in JavaScript
Writing JavaScript in a practical functional style — pure functions, immutability by convention, higher-order functions, currying, and composition.
Functional Patterns in JavaScript
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A pure function always returns the same output for the same input and causes no side effects anywhere else — no mutating an argument, no writing to a shared variable, no network call — which makes it as predictable to reason about as a plain math function.
- JavaScript has no enforced immutability for objects and arrays outside of `Object.freeze` (which only shallow-freezes, and silently does nothing in non-strict code if you try to violate it) — treating data as immutable in this language is a convention you and your team follow, like always returning a new array from `[...arr, newItem]` instead of calling `arr.push(newItem)`.
- A higher-order function either takes another function as an argument, returns one, or both — you've already been using this pattern every time you passed a callback to `map`, `filter`, or `reduce`; the functional style just makes writing your *own* higher-order functions a deliberate, everyday tool instead of something only built-ins do.
- Currying turns a function that takes several arguments into a sequence of functions that each take one, letting you build specialized versions of a general function by supplying some of its arguments early (`const double = multiply(2)`) and the rest later.
- Composition chains small, single-purpose pure functions into a pipeline — `pipe(parse, validate, save)` — instead of nesting calls or writing one function that does all three jobs at once, so each step stays independently readable, testable, and reusable.
The problem functional style is actually solving
The usual way a bug becomes hard to find is that something changed far from where you’re looking. A function three files away mutated an object your code also holds a reference to, and now you’re debugging symptoms instead of causes. Functional programming, at its core, is a set of habits aimed squarely at that problem: write functions whose behavior depends only on their inputs, and whose only effect is their return value, and a whole category of “something changed somewhere I wasn’t looking” bugs simply can’t occur — there’s nowhere for them to hide.
JavaScript was never built as a functional language the way Haskell or Elm were. There’s no enforcement mechanism forcing you to write this way. What you get instead is a style — a set of patterns you can choose to follow, borrowed from functional languages, that make ordinary JavaScript easier to reason about. That’s the scope of this lesson: practical functional habits you can start using today, not functional programming theory for its own sake.
Pure functions: the foundation everything else builds on
A function is pure if it satisfies two conditions: given the same inputs, it always returns the same output, and calling it causes no observable change to anything outside itself — no mutated argument, no write to a variable outside its own scope, no console log, no network request.
// Impure: depends on and mutates something outside its inputs
let total = 0;
function addToTotal(n) {
total += n;
return total;
}
// Pure: output depends only on the inputs, nothing outside is touched
function add(a, b) {
return a + b;
}
add behaves like a math function — you can call it a thousand times with
the same arguments and never worry about what happened the last 999 times.
addToTotal can’t make that promise; its return value depends on hidden
state, and calling it changes that state for everyone else too. The
embedded video builds this distinction from the ground up and is worth
watching closely here, since almost everything else in this lesson is a
consequence of taking pure functions seriously.
Immutability: a convention, not a guarantee
Functional style leans hard on not mutating data — instead of changing an
array or object in place, you produce a new one with the change applied.
The catch, worth being explicit about: JavaScript does not enforce this.
Object.freeze(obj) stops top-level reassignment of obj’s own
properties, but it’s shallow — freeze an object with a nested array inside
it, and that nested array is still completely mutable. And in non-strict
code, writing to a frozen property doesn’t even throw; it just silently
does nothing.
So “immutable” in everyday JavaScript means something more modest: your
team agrees to write { ...user, age: 38 } instead of user.age = 38, and
[...cart, item] instead of cart.push(item), as a discipline, not
because the language stops you from doing otherwise. That discipline is
what keeps functions pure — a function that returns a new array instead of
mutating the one it was given can’t have the kind of hidden side effect
that broke addToTotal above.
Higher-order functions: not new, just generalized
If you’ve used map, filter, or reduce, you’ve already used a
higher-order function — one that takes another function as an argument,
returns one, or both. The functional style just takes that pattern you
already know from the built-ins and applies it deliberately in your own
code:
function withLogging(fn) {
return (...args) => {
console.log(`calling with`, args);
return fn(...args);
};
}
const loggedAdd = withLogging(add);
loggedAdd(2, 3); // logs "calling with [2, 3]", returns 5
withLogging takes a function and returns a new one wrapping it — nothing
exotic, just the same shape as map’s callback pattern, pointed at
whole functions instead of array elements.
Currying: specializing a function by giving it less at once
Currying rewrites a function that takes several arguments into a chain of functions that each take one argument at a time:
const multiply = a => b => a * b;
const double = multiply(2);
double(5); // 10
double(9); // 18
multiply(2) doesn’t compute anything yet — it returns a new function
that remembers a = 2 and is waiting for b. That lets you build
specialized, reusable functions (double) out of a general one
(multiply) by supplying part of the input ahead of time. The “go deeper”
video on currying is a good next stop if you want several more worked
examples of exactly this pattern before moving on.
Composition: building pipelines out of small functions
Once your functions are pure and take a consistent shape, you can chain them — feeding one’s output into the next’s input — instead of nesting calls or writing one large function that does several jobs at once:
const pipe = (...fns) => input => fns.reduce((value, fn) => fn(value), input);
const clean = pipe(
s => s.trim(),
s => s.toLowerCase(),
s => s.replace(/\s+/g, '-'),
);
clean(' Hello World '); // "hello-world"
Each step in clean does exactly one thing and can be tested and reused on
its own. That’s the actual payoff of this whole lesson: pure functions are
what make composing them safe in the first place — compose two functions
with hidden side effects and you’ve just hidden two bugs instead of one,
in an order that’s now harder to trace than ever.
Where this fits in the path
This lesson leans on closures (a curried function’s inner functions are
closures over the arguments already supplied) and on the array methods
you’ve already learned (map, filter, and reduce are the higher-order
functions you met first, before this lesson generalized the pattern).
From here, functional style becomes a lens you can apply to code you
already know how to write — it’s not a separate track of the language, it’s
a way of using the parts you already have more deliberately.
Check yourself
Is `function addToCart(cart, item) { cart.push(item); return cart; }` a pure function? Why or why not?
No. Even though it returns a value, it mutates its `cart` argument in place via `push` — that's a side effect visible to whatever else holds a reference to that same array. A pure version would return a new array instead, e.g. `[...cart, item]`, leaving the original untouched.
Does `Object.freeze` give JavaScript real, enforced immutability?
Not fully. `Object.freeze` prevents adding, removing, or reassigning an object's own top-level properties, but it's shallow — a frozen object's nested objects or arrays can still be mutated freely. It also fails silently rather than throwing in non-strict-mode code. Real immutability in JS is mostly a convention the codebase agrees to follow, not something the language forces on every value.
What makes a function "higher-order," and is `array.map(callback)` an example of one?
A higher-order function is one that takes a function as an argument, returns a function, or both. `map` qualifies on the first count — it takes the `callback` function as an argument — making `map` itself the higher-order function, with `callback` as the plain function it operates on.
What problem does currying actually solve — why not just call a multi-argument function with all its arguments every time?
Currying lets you supply some arguments once and reuse the resulting specialized function repeatedly with just the remaining ones, instead of re-passing the same fixed arguments over and over at every call site. `const formatUSD = formatCurrency('USD')` reads better and avoids repetition compared to calling `formatCurrency('USD', amount)` everywhere `amount` changes.
Why would you write `pipe(parseInput, validate, save)` instead of one function that does all three steps inline?
Each of `parseInput`, `validate`, and `save` can be tested, reused, and reasoned about on its own — and the pipeline itself documents the order of operations at a glance. A single function doing all three mixes concerns together, so a bug in validation and a bug in saving both have to be hunted for in the same block of code instead of two separately testable functions.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.