Functional Programming in JavaScript
Functional Programming (FP) is a paradigm that treats computation as the evaluation of pure functions and avoids changing state or mutable data. JavaScript's first-class functions, closures, and array methods make it an excellent language for applying FP principles.
What is Functional Programming?
Functional Programming (FP) is a programming paradigm — a style of building programs — that emphasises writing software using pure functions, avoiding shared state, mutable data, and side effects. It's declarative rather than imperative: you describe what you want, not how to get it.
JavaScript is a multi-paradigm language that supports object-oriented, imperative, and functional styles. You don't have to choose one exclusively — but understanding FP principles will help you write cleaner, more predictable, and more testable code.
Imperative vs Functional Style
The clearest way to understand FP is to compare it to the imperative (step-by-step) style you may already know:
// ── IMPERATIVE: mutate a variable in a loop ──
const numbers = [1, 2, 3, 4, 5];
let doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
console.log(doubled); // [2, 4, 6, 8, 10]
// ── FUNCTIONAL: pure transformation with map ──
const nums = [1, 2, 3, 4, 5];
const doubledFP = nums.map(n => n * 2);
console.log(doubledFP); // [2, 4, 6, 8, 10]
console.log(nums); // [1, 2, 3, 4, 5] ← original unchanged!
Pure Functions
A pure function follows two strict rules:
1. Deterministic — Given the same arguments, it always
returns the same result.
2. No side effects — It doesn't modify anything
outside its own scope (no DOM changes, no console.log, no HTTP calls, no modifying arguments).
// ✅ PURE — same input → same output, no side effects
function add(a, b) {
return a + b;
}
add(2, 3); // always 5
// ❌ IMPURE — relies on external state
let tax = 0.18;
function calcPrice(price) {
return price + (price * tax); // depends on outer 'tax'
}
// ✅ PURE version — tax is passed as argument
function calcPricePure(price, taxRate) {
return price + (price * taxRate);
}
calcPricePure(100, 0.18); // always 118 ✓
// ❌ IMPURE — modifies external array
const cart = ["apple", "bread"];
function addItem(item) {
cart.push(item); // mutates external state!
}
// ✅ PURE — returns new array
function addItemPure(cart, item) {
return [...cart, item]; // spread creates new array
}
Immutability
Immutability means never directly modifying data. Instead of changing an existing object or array, you create a new one with the desired changes. This prevents a whole class of bugs caused by unintended mutations.
// ── OBJECTS ───────────────────────────────────────
const user = { name: "Alice", age: 28 };
// ❌ Mutable — modifies original
user.age = 29;
// ✅ Immutable — spread creates new object
const updatedUser = { ...user, age: 29 };
// ── ARRAYS ────────────────────────────────────────
const items = ["a", "b", "c"];
// ❌ Mutates original
items.push("d");
items.splice(1, 1);
// ✅ Immutable alternatives
const withD = [...items, "d"]; // add item
const without1 = items.filter((_, i) => i !== 1); // remove index 1
const updated = items.map((v, i) => i === 0 ? "A" : v); // update
// ── NESTED OBJECTS ────────────────────────────────
const state = {
user: { name: "Bob", prefs: { theme: "dark" } }
};
// ✅ Deep immutable update (spread at each level)
const newState = {
...state,
user: {
...state.user,
prefs: { ...state.user.prefs, theme: "light" }
}
};
const makes a variable binding immutable — it doesn't freeze
the object itself. Use Object.freeze() for shallow
immutability, or libraries like Immer for deep immutable state management in
React.
Higher-Order Functions
A higher-order function (HOF) is a function that either takes one or more functions as arguments, or returns a function as its result — or both. HOFs are the workhorse of functional JavaScript.
const products = [
{ name: "Laptop", price: 75000, inStock: true },
{ name: "Mouse", price: 800, inStock: true },
{ name: "Monitor", price: 22000, inStock: false },
{ name: "Keyboard",price: 1500, inStock: true },
];
// map — transform each item
const names = products.map(p => p.name);
// ["Laptop", "Mouse", "Monitor", "Keyboard"]
// filter — keep items matching a condition
const available = products.filter(p => p.inStock);
// [{Laptop}, {Mouse}, {Keyboard}]
// reduce — accumulate into a single value
const totalValue = products
.filter(p => p.inStock)
.reduce((acc, p) => acc + p.price, 0);
// 77300
// Chain them together declaratively
const affordable = products
.filter(p => p.inStock && p.price < 5000)
.map(p => p.name)
.sort();
// ["Keyboard", "Mouse"]
// A HOF that returns a specialised multiplier
function multiplier(factor) {
return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
const tenTimes = multiplier(10);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(tenTimes(5)); // 50
// HOF accepting a function argument
function repeat(fn, times) {
return (x) => {
let result = x;
for (let i = 0; i < times; i++) result = fn(result);
return result;
};
}
const quadruple = repeat(double, 2); // double twice
console.log(quadruple(3)); // 12
Currying & Partial Application
Currying transforms a function that takes multiple
arguments into a sequence of functions each taking a single argument. Instead of f(a, b, c), you call f(a)(b)(c). This enables powerful patterns like
partial application — pre-filling some arguments to create specialised
functions.
// ── Manual currying ────────────────────────────────
function add(a) {
return function(b) {
return a + b;
};
}
add(2)(3); // 5
// Arrow function shorthand
const multiply = a => b => a * b;
multiply(4)(5); // 20
// ── Partial Application ────────────────────────────
const greet = greeting => name => `${greeting}, ${name}!`;
const sayHello = greet("Hello"); // partial application
const sayNamaste = greet("Namaste");
sayHello("Alice"); // "Hello, Alice!"
sayHello("Bob"); // "Hello, Bob!"
sayNamaste("Riya"); // "Namaste, Riya!"
// ── Generic curry utility ──────────────────────────
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function(...moreArgs) {
return curried(...args, ...moreArgs);
};
};
}
const sum = curry((a, b, c) => a + b + c);
sum(1)(2)(3); // 6
sum(1, 2)(3); // 6
sum(1)(2, 3); // 6
Function Composition
Function composition means combining multiple functions so the output of one becomes the input of the next. It's the mathematical idea of f(g(x)) applied to programming. You build complex behaviour from simple, reusable functions.
// ── Building blocks ───────────────────────────────
const trim = str => str.trim();
const toLowerCase = str => str.toLowerCase();
const addGreeting = str => `Hello, ${str}!`;
const exclaim = str => str + " 🎉";
// ── Manual nesting (right-to-left) ────────────────
const result = addGreeting(toLowerCase(trim(" ALICE ")));
console.log(result); // "Hello, alice!"
// ── compose utility (right-to-left like math) ─────
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const processName = compose(addGreeting, toLowerCase, trim);
processName(" ALICE "); // "Hello, alice!"
// ── pipe utility (left-to-right, more readable) ───
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const processName2 = pipe(trim, toLowerCase, addGreeting, exclaim);
processName2(" BOB "); // "Hello, bob! 🎉"
// ── Real-world pipeline ───────────────────────────
const getDiscountedTotal = pipe(
items => items.filter(i => i.inStock),
items => items.map(i => i.price),
prices => prices.reduce((s, p) => s + p, 0),
total => total * 0.9 // 10% discount
);
pipe more intuitive. Libraries like Ramda and
lodash/fp ship these utilities built-in.
Functional vs Object-Oriented Programming
FP and OOP are complementary paradigms. JavaScript supports both — knowing the trade-offs helps you choose the right tool for the job:
| Aspect | Functional (FP) | Object-Oriented (OOP) |
|---|---|---|
| Core unit | Functions | Objects & Classes |
| State | Immutable — avoided | Encapsulated within objects |
| Side effects | Minimised / isolated | Managed via methods |
| Code reuse | Composition, HOFs | Inheritance, mixins |
| Predictability | High — pure functions | Depends on encapsulation |
| Good for | Data transformation, pipelines | Modelling real-world entities |
| JS examples | map/filter/reduce, React hooks | ES6 Classes, DOM APIs |
Closures — FP's Secret Weapon
Closures are what make FP patterns like currying and memoization possible in JavaScript. A closure is a function that remembers the variables from its outer scope even after that scope has finished executing.
// ── Memoization using closures ────────────────────
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;
};
}
const expensiveCalc = memoize((n) => {
console.log("computing...");
return n * n;
});
expensiveCalc(10); // computing... → 100
expensiveCalc(10); // (from cache) → 100
expensiveCalc(5); // computing... → 25
// ── Counter using closure (no mutation of outside state) ──
function makeCounter(start = 0) {
let count = start; // private to this closure
return {
increment: () => ++count,
decrement: () => --count,
value: () => count
};
}
const counter = makeCounter(10);
counter.increment(); // 11
counter.increment(); // 12
counter.value(); // 12
Where to Apply FP in Real Projects
You don't need to go full FP — adopt the patterns that improve your codebase:
Try It Yourself
Which of the following best describes a pure function?
- Functional Programming treats computation as evaluation of pure functions — deterministic, no side effects.
- Immutability means never mutating data — use spread (
...),map, andfilterto return new structures. - Higher-order functions like
map,filter, andreduceare the backbone of FP in JS. - Currying transforms multi-argument functions into chains of single-argument functions, enabling partial application.
- Function composition (
pipe/compose) combines small functions into powerful data pipelines. - Closures power FP patterns like memoization, currying, and private state.
- FP and OOP are complementary — modern JS (React, Redux) blends both effectively.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.