Functional Programming
Functional Programming treats computation as evaluation of pure mathematical functions. Learn pure functions, immutability, higher-order functions, currying, function composition, and memoization — and see how they power React, Redux, and modern JavaScript.
What is functional programming in JavaScript?
Functional programming builds programs from small pure functions, which return the same output for the same input and have no side effects, and treats data as immutable. In JavaScript this mostly means using map, filter and reduce instead of loops that mutate, returning new objects instead of changing old ones, and composing small functions into bigger ones.
const users = [{ name: "Ada", active: true }, { name: "Bob", active: false }];
const activeNames = users
.filter((u) => u.active)
.map((u) => u.name); // ["Ada"]
const total = cart.reduce((sum, item) => sum + item.price, 0);
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);FP Concepts Quick Reference
| Concept | Definition | JS Example |
|---|---|---|
| Pure function | Same input → same output, no side effects | const add = (a, b) => a + b |
| Immutability | Never mutate; return new data | { ...obj, key: newVal } |
| First-class fn | Functions are values you can pass/return | const fn = x => x * 2 |
| Higher-order fn | Function that takes or returns a function | .map(), .filter(), .reduce() |
| Currying | f(a, b) → f(a)(b) — partial application | const add = a => b => a + b |
| Composition | Chain f(g(x)) — small fns → big transforms | pipe(trim, lower, slugify) |
| Referential transparency | Expression can be replaced by its value | memoize enables this |
| Functor | Container you can map over safely | Array, Promise, Maybe |
Common Pitfalls
Interactive Demo
Code Editor
<pre id="out"></pre>Preview
Functional programming — step by step
Pure functions — the foundation
A pure function always returns the same output for the same inputs and produces no observable side effects (no mutation, no I/O, no random). Pure functions are trivially testable (no mocking required), composable, memoizable, and safe to parallelize. The goal of FP is to maximize the percentage of your code that is pure functions.
🎯 Quick Check
What makes a function 'pure'?
Functional Programming in JavaScript: summary
Key points
- Pure functions are easy to test and reason about.
- Immutable updates (
{ ...obj, key },toSorted(),with()) avoid shared-state bugs. - Higher-order functions take or return functions:
map,debounce, middleware. - Readability beats cleverness; a plain loop is fine when it's clearer.
Frequently asked questions
›What is a pure function?
A function that always returns the same result for the same arguments and doesn't change anything outside itself (no mutation, I/O or globals).