Tutorials JavaScript Functional Programming
Ch 65 / 78
Chapter 65 Advanced 9 min read JavaScript

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 you'll learn
What Functional Programming is and why it matters
Pure functions and how to write them
Immutability and avoiding side effects
Higher-order functions: map, filter, reduce
Currying and partial application
Function composition with compose & pipe

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.

Declarative
Focus on what to compute, not how. Use expressions instead of statements.
Pure Functions
Same input always produces same output. No side effects — no mutation of external state.
Immutability
Data is never changed after creation. Instead, new data structures are returned.
First-Class Functions
Functions are values — they can be passed as arguments, returned, and stored in variables.

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:

JS — Imperative vs Functional
// ── 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!
Key Insight
The functional version never mutates the original array. It produces a new array — making the code easier to reason about and test in isolation.

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).

JS — Pure vs Impure Functions
// ✅ 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
}
Testable
Pure functions need no mocks or setup — just call with input and assert the output.
Cacheable (Memoizable)
Since same input → same output, you can cache results to avoid redundant computation.
Composable
Pure functions snap together like LEGO — output of one becomes input of another.
Easier to Debug
No hidden state changes. Bugs are isolated to the function's own logic.

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.

JS — Immutable Patterns
// ── 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" }
    }
};
Note
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.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Functional methods, ES6+ patterns — all on one page.
Get Sheet

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.

JS — map · filter · reduce
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"]
JS — Functions returning Functions (HOF)
// 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.

Normal add(2, 3) → 5
Curried add(2)(3) → 5
Partial const add2 = add(2); add2(3); → 5
JS — Currying
// ── 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.

input
→
trim()
→
toLowerCase()
→
addGreeting()
→
output
JS — compose & pipe
// ── 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
);
Pro Tip
pipe reads left-to-right (data flows forward), while compose reads right-to-left (like math notation). Most developers find pipe more intuitive. Libraries like Ramda and lodash/fp ship these utilities built-in.
Advertisement

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
Note
Modern JavaScript development often blends both paradigms. React uses functional components and hooks (FP), but Node.js frameworks like NestJS are class-based (OOP). Use what fits the problem — not dogma.

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.

JS — Closures powering FP patterns
// ── 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:

Data Filtering
State Management
Unit Testing
API Data Pipelines
React Components
Event Handlers
Middleware Chains
Performance Optim.
FP Libraries in JS
Ramda — 100% pure FP utilities, auto-curried. Lodash/fp — FP-flavoured lodash. Immer — immutable state with mutable-looking syntax. RxJS — reactive programming with observable streams.

Try It Yourself

Live Editor
✎ Editor
👁 Preview
Common Mistake
Confusing pure functions with arrow functions. An arrow function is just a syntax shorthand — it can still have side effects. A pure function is defined by its behaviour (deterministic + no side effects), not its syntax.
Quick Check — Chapter 65

Which of the following best describes a pure function?

Chapter Summary
  • Functional Programming treats computation as evaluation of pure functions — deterministic, no side effects.
  • Immutability means never mutating data — use spread (...), map, and filter to return new structures.
  • Higher-order functions like map, filter, and reduce are 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel