Skip to content
jshacks.dev
Functions

Functional Programming in JavaScript The Complete Guide

A complete guide to functional programming in JavaScript: pure functions, immutability, map, filter, reduce, composition, currying and errors as values.

29 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Node.js and npm logos.

Functional programming is a way of building programs out of functions that take values and return values, with as little hidden state and as few side effects as you can manage. In JavaScript it is not an all-or-nothing choice, because the language lets you write in several styles, and the functional parts, map, filter, reduce, arrow functions, spread, const and closures, are some of the most used features in everyday code. The reason people reach for the style is practical. Code made of pure functions is easier to test, since the same input always gives the same output, easier to reason about, since nothing else can change the data under you, and easier to compose, since small functions fit together like parts. This guide explains the ideas in the order that they build on each other: what makes a function pure, how to treat data as immutable, how higher-order functions replace loops, how closures give you partial application and currying, how composition and pipelines assemble programs, how to handle absence and failure without exceptions, how recursion and laziness fit and where the style costs more than it gives. Every example shows its exact output on Node.js 24.

What functional programming is and is not

The core of the style is a handful of ideas, and each has a plain meaning in JavaScript.

Pure functions. A function whose result depends only on its arguments, and which changes nothing outside itself.

Immutable data. Values are not changed after they are created. To "change" something you build a new value.

Functions as values. Functions are passed to other functions, returned from functions and stored in data, which JavaScript supports because functions are first-class.

Declarative code. You say what you want, as in "the names of the paid orders", and let functions such as filter and map do the looping, instead of writing out the loop, counters and temporary arrays.

Composition. Big behavior is built by connecting small functions, with the output of one becoming the input of the next.

What it is not: it is not a requirement to avoid classes, loops or mutation everywhere, it is not a set of obscure terms from category theory, and it is not automatically faster or slower. JavaScript is a multi-paradigm language, and the most useful approach is a hybrid: write the logic of the program as pure functions over plain data, and keep the parts that must have effects, such as reading input, writing files and updating a screen, in a thin layer around them. The same program written two ways shows the difference.

JavaScript
const orders = [
  { id: 1, customer: "Ana", total: 40, paid: true },
  { id: 2, customer: "Bo", total: 15, paid: false },
  { id: 3, customer: "Ana", total: 25, paid: true },
  { id: 4, customer: "Cy", total: 60, paid: true },
];

// imperative: how to do it
const totals = {};

for (let i = 0; i < orders.length; i++) {
  if (orders[i].paid) {
    if (totals[orders[i].customer] === undefined) totals[orders[i].customer] = 0;

    totals[orders[i].customer] += orders[i].total;
  }
}

// functional: what is wanted
const paidTotals = orders
  .filter((order) => order.paid)
  .reduce(
    (result, order) => ({
      ...result,
      [order.customer]: (result[order.customer] ?? 0) + order.total,
    }),
    {},
  );

console.log(totals, paidTotals);
Text
{ Ana: 65, Cy: 60 } { Ana: 65, Cy: 60 }

Both versions compute the same thing. The first mutates a totals object, tracks an index and checks for missing keys by hand. The second reads as a description: keep the paid orders, then fold them into an object keyed by customer. It creates a new object at each step, which a later section looks at as a cost.

Pure functions

A function is pure if two conditions hold. Given the same arguments, it always returns the same result. And it has no side effects, meaning it does not change anything that it did not create: no global variables, no arguments, no files, no network, no screen. Everything the function depends on is in its parameter list, and everything it does shows up in its return value.

JavaScript
// impure: the result depends on, and changes, hidden state
let counter = 0;

function nextId() {
  counter += 1;

  return counter;
}

// pure: the state goes in as an argument and comes out as a result
function nextIdPure(current) {
  return { id: current + 1, counter: current + 1 };
}

console.log(nextId(), nextId());
console.log(nextIdPure(0), nextIdPure(0));
Text
1 2
{ id: 1, counter: 1 } { id: 1, counter: 1 }

nextId gives a different answer on each call, since it depends on counter, which it also changes. nextIdPure returns the same answer for the same input every time. The caller is now responsible for carrying the state forward, and that responsibility is the price and the point: every change of state is visible at the place where it happens.

Hidden inputs and outputs

The impurities that cause trouble are the ones you do not see in the signature. Reading the clock with Date.now(), generating a number with Math.random(), reading process.env, reading a variable from the enclosing module and calling console.log all make a function impure. The cure is to pass such things in.

JavaScript
// hard to test
function isExpired(token) {
  return token.expiresAt < Date.now();
}

// pure: time is an argument
function isExpiredAt(token, now) {
  return token.expiresAt < now;
}

const token = { expiresAt: 1000 };

console.log(isExpiredAt(token, 999), isExpiredAt(token, 1001));
Text
false true

The second version can be tested with any clock value you like, and it works the same on every run. The program still needs the real time somewhere, and a thin outer function supplies it: isExpiredAt(token, Date.now()). Splitting each feature into a pure core and an impure shell is the most practical habit that this style teaches.

Why purity pays

Pure functions are easy to test, since you need no setup and no mocks, just inputs and the expected output. They are easy to understand, since you can read one without knowing the state of the rest of the program. They can be cached, since a result for a given input never changes, so memoization is safe. They can be run in any order, or in parallel, since they do not interfere. And they can be replaced by their result, which is what is meant by referential transparency: wherever you see add(2, 3), you could write 5 and the program would behave the same.

JavaScript
function memoize(fn) {
  const cache = new Map();

  return (arg) => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));

    return cache.get(arg);
  };
}

let calls = 0;
const square = memoize((n) => {
  calls += 1;

  return n * n;
});

console.log(square(12), square(12), square(5), calls);
Text
144 144 25 2

The cache is only correct because square is pure. If it depended on the clock, the cached result would be stale.

What counts as a side effect

Mutating an argument is the most common unintended one.

JavaScript
function addTag(post, tag) {
  post.tags.push(tag);

  return post;
}

function addTagPure(post, tag) {
  return { ...post, tags: [...post.tags, tag] };
}

const original = { title: "Hello", tags: ["intro"] };

addTag(original, "js");

console.log(original.tags);

const untouched = { title: "Hello", tags: ["intro"] };
const updated = addTagPure(untouched, "js");

console.log(untouched.tags, updated.tags);
Text
[ 'intro', 'js' ]
[ 'intro' ] [ 'intro', 'js' ]

The first function changed the object that its caller passed, so every other holder of that object saw the change. The second left it alone and returned a new object. Other side effects are throwing an exception, logging, writing a file, making a request and changing the DOM. A program needs those. The goal is to keep them at the edges, and to make each one visible.

Immutable data

If functions must not change their inputs, the data they receive must be treated as read-only. JavaScript does not enforce that by default, so immutability is a habit supported by a few tools.

const prevents reassigning a variable, but not changing the object it holds, so it is not immutability.

JavaScript
const list = [1, 2, 3];

list.push(4);

console.log(list);

try {
  list = [];
} catch (error) {
  console.log(error.message);
}
Text
[ 1, 2, 3, 4 ]
Assignment to constant variable.

Updating without mutating

The standard techniques build a new value from the old one, and they are worth knowing as a set.

TaskMutating formNon-mutating form
Add to an arraylist.push(x)[...list, x]
Remove by indexlist.splice(i, 1)list.toSpliced(i, 1) or list.filter((_, n) => n !== i)
Replace by indexlist[i] = xlist.with(i, x) or list.map((item, n) => (n === i ? x : item))
Sortlist.sort(cmp)list.toSorted(cmp)
Reverselist.reverse()list.toReversed()
Set a propertyobj.key = x{ ...obj, key: x }
Remove a propertydelete obj.keyconst { key, ...rest } = obj
MergeObject.assign(a, b){ ...a, ...b }
JavaScript
const state = { user: { name: "Ana", age: 30 }, tags: ["a", "b"], count: 1 };

const next = {
  ...state,
  user: { ...state.user, age: 31 },
  tags: state.tags.toSpliced(0, 1),
  count: state.count + 1,
};

console.log(state);
console.log(next);
console.log(state.user === next.user, state.tags === next.tags);
Text
{ user: { name: 'Ana', age: 30 }, tags: [ 'a', 'b' ], count: 1 }
{ user: { name: 'Ana', age: 31 }, tags: [ 'b' ], count: 2 }
false false

The original object is untouched. Every part of the path that changed got a new object: the root, user and tags. A part that did not change can be shared between the old and the new value, and that sharing is cheap, which is called structural sharing. Here state.user and next.user differ because age changed. If only count had changed, next.user would be the same object as state.user, and that identity is what lets UI libraries skip re-rendering parts that did not change.

The spread syntax copies one level, so a nested update needs a spread at every level of the path, as above. For deeply nested state, this gets verbose, and a helper library such as Immer lets you write the update as if you were mutating a draft and produces the immutable result for you.

Freezing

Object.freeze makes an object read-only at runtime, in strict mode with an error, and it is shallow. A freeze in development is a good way to find code that mutates data it should not.

JavaScript
const settings = Object.freeze({ theme: "dark", sizes: Object.freeze([12, 14]) });

try {
  settings.theme = "light";
} catch (error) {
  console.log(error.message);
}

console.log(settings.theme, Object.isFrozen(settings.sizes));
Text
Cannot assign to read only property 'theme' of object '#<Object>'
dark true

Freezing costs a little on creation and prevents bugs that are otherwise very hard to find, which makes it a reasonable default for configuration and for state in development builds. For a deep copy of data that you will change, structuredClone copies dates, maps, sets and cycles, and refuses functions.

The cost of copying

Building a new array or object on each change costs time and memory proportional to its size, and a loop that copies a growing array on every step is quadratic. The pattern to watch for is reduce with a spread in the accumulator, which copies the whole result every time.

JavaScript
const words = ["a", "b", "a", "c", "b", "a"];

const countsSlow = words.reduce((counts, word) => ({ ...counts, [word]: (counts[word] ?? 0) + 1 }), {});

const countsFast = new Map();

for (const word of words) countsFast.set(word, (countsFast.get(word) ?? 0) + 1);

console.log(countsSlow, countsFast);
Text
{ a: 3, b: 2, c: 1 } Map(3) { 'a' => 3, 'b' => 2, 'c' => 1 }

For six words nothing matters. For a million, the spread version does enormous copying while the loop does not. The practical rule that many functional JavaScript programmers settle on is to allow mutation of data that a function creates and owns, as the Map here, so long as nothing outside can see it. The function is still pure from the outside: same input, same output, no visible change. We give no timings, since they depend on the engine, and the reasoning about growth is enough to guide the choice.

Higher-order functions replace loops

A higher-order function takes a function as an argument, returns one, or both. The array methods map, filter and reduce are the three that do most of the daily work, and each one captures a common loop shape so that you do not have to write it.

JavaScript
const prices = [10, 25, 40, 5, 60, 15];

console.log(prices.map((price) => price * 2));
console.log(prices.filter((price) => price >= 25));
console.log(prices.reduce((sum, price) => sum + price, 0));
Text
[ 20, 50, 80, 10, 120, 30 ]
[ 25, 40, 60 ]
155

map turns a list into a list of the same length, by applying a function to each item. filter keeps the items for which a test returns true. reduce folds a list into one value, by carrying an accumulator through the list, and it is the most general of the three: you can write both map and filter with it. Money is better kept in whole cents than in decimals, which is why these prices are integers.

Choosing the right method

The art is picking the method that says what you mean. A loop says nothing about its purpose until you read the body, and each array method announces it.

You wantMethod
The same number of items, changedmap
A subsetfilter
One value from the listreduce, or sum-style helpers
The first matchfind
Whether any or all items passsome, every
Nested lists made flatflat, flatMap
Items grouped by a keyObject.groupBy, Map.groupBy
A side effect for each itemforEach, or a for...of loop
A sorted copytoSorted

Reaching for reduce when a simpler method exists makes code harder to read. list.reduce((acc, x) => [...acc, x * 2], []) is list.map((x) => x * 2), and the second is shorter and clearer. Use reduce when the result has a different shape from the input, such as a total, an object indexed by key or a count of each value.

JavaScript
const words = ["apple", "avocado", "banana", "blueberry", "cherry"];

const grouped = words.reduce((groups, word) => {
  const key = word[0];

  return { ...groups, [key]: [...(groups[key] ?? []), word] };
}, {});

console.log(grouped);
console.log(Object.groupBy(words, (word) => word[0]));
Text
{
  a: [ 'apple', 'avocado' ],
  b: [ 'banana', 'blueberry' ],
  c: [ 'cherry' ]
}
[Object: null prototype] {
  a: [ 'apple', 'avocado' ],
  b: [ 'banana', 'blueberry' ],
  c: [ 'cherry' ]
}

The built-in Object.groupBy, in Node.js 21 and later, does what the hand-written reduce does, in one call, which is a good example of the standard library absorbing a pattern.

Writing your own higher-order functions

The same idea applies to your own code. Any time you see two functions that differ only in one step, extract the step and pass it in.

JavaScript
function retry(times, task) {
  let lastError;

  for (let attempt = 1; attempt <= times; attempt++) {
    try {
      return task(attempt);
    } catch (error) {
      lastError = error;
    }
  }

  throw lastError;
}

console.log(
  retry(3, (attempt) => {
    if (attempt < 3) throw new Error("fail " + attempt);

    return "succeeded on attempt " + attempt;
  }),
);
Text
succeeded on attempt 3

retry owns the loop, the counting and the error handling, and the task decides what to do. The same function works for a network call, a file read or a calculation, because it knows nothing about them. That is the payoff of treating functions as values.

Partial application and currying

A function with several parameters can be turned into functions with fewer, by fixing some arguments in advance. Closures make this natural, since the returned function remembers the arguments it was given.

JavaScript
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);

const greet = (greeting, punctuation, name) => `${greeting}, ${name}${punctuation}`;
const hello = partial(greet, "Hello", "!");

console.log(hello("Ana"), hello("Bo"));

const add = (a) => (b) => a + b;
const increment = add(1);

console.log([1, 2, 3].map(increment), add(10)(5));
Text
Hello, Ana! Hello, Bo!
[ 2, 3, 4 ] 15

partial fixes any number of leading arguments, and add is written in curried form, where each function takes one argument and returns the next. Currying pays off when the arguments differ in how often they change: configuration first, data last. A function written as (config) => (data) => result can be built once and then mapped over a list, as increment was. The reason that many functional libraries put the data last is exactly this.

Composition and pipelines

Composition connects functions so that the output of one is the input of the next. pipe runs them left to right, in the order you would read them, and compose runs them right to left, as in mathematical notation.

JavaScript
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const compose = (...fns) => (input) => fns.reduceRight((value, fn) => fn(value), input);

const trim = (text) => text.trim();
const lower = (text) => text.toLowerCase();
const words = (text) => text.split(/\s+/);
const count = (list) => list.length;

const wordCount = pipe(trim, lower, words, count);

console.log(wordCount("  Hello Big World "));
console.log(compose(count, words, lower, trim)(" A B "));
Text
3
2

Each step is a small function that can be tested alone and reused, and the pipeline reads as a list of what happens. The two forms give the same result when the function order is mirrored. In the pipeline, a function in the middle should take one argument and return one value. Functions that need more arguments are adapted by partial application first.

JavaScript
const tap = (effect) => (value) => {
  effect(value);

  return value;
};

const slug = pipe(
  trim,
  tap((value) => console.log("after trim:", JSON.stringify(value))),
  lower,
  (text) => text.replace(/\s+/g, "-"),
);

console.log(slug("  Functional Programming "));
Text
after trim: "Functional Programming"
functional-programming

tap inserts a side effect, here a log, in the middle of a pipeline without changing the value, which is the standard way to debug one. Method chaining on arrays, list.filter(...).map(...), is a pipeline too, with the methods as the steps, and for arrays it is usually the clearest form. pipe is for chains of your own functions.

Point-free style, and its limit

Point-free means writing a function without naming its argument, as in const double = multiply(2) instead of const double = (n) => multiply(2)(n). Used lightly it is neat. Used heavily it hides what the function does.

JavaScript
console.log(["1", "2", "3"].map(Number));
console.log(["1", "2", "3"].map(parseInt));
Text
[ 1, 2, 3 ]
[ 1, NaN, NaN ]

The first line works since Number takes one argument. The second fails because map passes the index as a second argument, and parseInt reads it as the radix. Point-free code passes a function to someone else's call, so you must know exactly what arguments it will receive. If you are not sure, write the arrow.

Handling absence and failure as values

Exceptions are a side effect: they jump out of the function to somewhere else. A functional program prefers to return failure as a value, so that the possibility is visible in the result and the caller must deal with it. JavaScript offers three light tools.

Optional chaining and nullish coalescing cover absence in plain data.

JavaScript
const user = { profile: { address: null } };

console.log(user.profile?.address?.city ?? "unknown");
Text
unknown

Result objects cover failure with a reason. A function returns an object that says whether it worked, and carries either the value or the error.

JavaScript
const ok = (value) => ({ ok: true, value });
const fail = (error) => ({ ok: false, error });

const parseJson = (text) => {
  try {
    return ok(JSON.parse(text));
  } catch (error) {
    return fail(error.message);
  }
};

const readPort = (config) => (config.port === undefined ? fail("no port") : ok(config.port));
const andThen = (result, fn) => (result.ok ? fn(result.value) : result);

console.log(andThen(parseJson('{"port":8080}'), readPort));
console.log(andThen(parseJson("{}"), readPort));
console.log(andThen(parseJson("{"), readPort));
Text
{ ok: true, value: 8080 }
{ ok: false, error: 'no port' }
{
  ok: false,
  error: "Expected property name or '}' in JSON at position 1 (line 1 column 2)"
}

andThen runs the next step only if the previous one succeeded, and passes a failure through unchanged, so a chain of steps stops at the first failure with its reason, with no nested if. Libraries such as fp-ts and Effect build a full toolkit on this idea, with types that make it safe in TypeScript. In plain JavaScript, a small convention like the one above is often enough.

Promises are the third: they already model a value that may fail, and async code with try and catch is the usual way to handle it.

The pragmatic rule is to throw for programmer errors and truly exceptional conditions, and to return values for failures that callers expect, such as invalid input and missing records.

Modeling data and state with plain values

A functional program keeps its state in plain data and describes changes as functions from the old state to the new one. The most common shape is the reducer: a pure function that takes the current state and an action and returns the next state.

JavaScript
function reducer(state, action) {
  switch (action.type) {
    case "add":
      return { ...state, items: [...state.items, action.item] };
    case "clear":
      return { ...state, items: [] };
    default:
      return state;
  }
}

const actions = [
  { type: "add", item: "a" },
  { type: "add", item: "b" },
  { type: "clear" },
  { type: "add", item: "c" },
];

const history = actions.reduce(
  (states, action) => [...states, reducer(states.at(-1), action)],
  [{ items: [] }],
);

console.log(history.map((state) => state.items.join("")));
console.log(actions.reduce(reducer, { items: [] }));
Text
[ '', 'a', 'ab', '', 'c' ]
{ items: [ 'c' ] }

Because the reducer is pure, the whole history of states is just a list that you can inspect, replay or test, and "undo" is nothing more than going back one item. This is the core of Redux and of the useReducer hook, and it works equally well on a server, in a game or in a command-line tool. The action objects are a tagged union: each has a type that says which shape it has, and the switch is the pattern match. TypeScript can check that every case is handled.

Recursion and folds

Functional code often replaces loops with recursion, since a recursive function has no counters to update. Many recursive functions are folds, and reduce is the fold, so the recursion is hidden in the library.

JavaScript
const sum = ([head, ...tail]) => (head === undefined ? 0 : head + sum(tail));

const flatten = (list) => list.reduce((flat, item) => flat.concat(Array.isArray(item) ? flatten(item) : item), []);

console.log(sum([1, 2, 3, 4]), flatten([1, [2, [3, [4]]]]));
Text
10 [ 1, 2, 3, 4 ]

These are fine for small data, but JavaScript engines do not optimize tail calls, so a recursion over a very long list ends with a RangeError: Maximum call stack size exceeded. For deep recursion, there are two escapes: use a loop or reduce, or use a trampoline, which turns each recursive call into a function that a loop runs.

JavaScript
const trampoline = (fn) => (...args) => {
  let result = fn(...args);

  while (typeof result === "function") result = result();

  return result;
};

const sumTo = trampoline(function sum(n, total = 0) {
  return n === 0 ? total : () => sum(n - 1, total + n);
});

console.log(sumTo(100000));
Text
5000050000

The function returns either a final value or a thunk, a function that holds the next step, and the loop in trampoline runs the thunks one at a time, so the stack never grows. In practice, use reduce or a loop inside a pure function. The trampoline is worth knowing, and rarely worth using.

Laziness

Eager code computes everything immediately. Lazy code computes only what is asked for, which allows infinite sequences and saves work when the consumer stops early. Generators and iterator helpers give JavaScript lazy sequences.

JavaScript
function* naturals() {
  let n = 1;

  while (true) yield n++;
}

const firstSquaresOfEvens = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(4)
  .toArray();

console.log(firstSquaresOfEvens);
Text
[ 4, 16, 36, 64 ]

The pipeline reads like one on arrays and processes one number at a time, so the infinite source is no problem. Iterator helpers are in Node.js 22 and later. The generators guide on this site covers them in full.

Functional programming in everyday code

The style rarely appears as a pure program. It appears as habits in ordinary code, and a few of them give most of the benefit.

Write the calculation parts of a program as pure functions of plain data, and keep reading, writing and rendering in a thin shell. Prefer map, filter and reduce for transforming lists, and use for...of when you need break, await or a clear loop. Do not mutate arguments, and return new values. Treat configuration and state as read-only, and freeze it in development to catch mistakes. Pass dependencies, such as the clock, a random source and a logger, as arguments instead of reading globals. Build small functions with one job and a good name, and combine them with pipe or plain calls. Return failure as a value when callers will check for it. Use closures to hold configuration, and keep them from holding large objects. And let tests be tables of inputs and outputs, since pure functions invite them.

A worked refactoring

The shift in thinking is easier to see on a real function than in the abstract. Start with a function that processes a list of signups and returns a report, written the way most of us first write it.

JavaScript
function summarize(users) {
  const result = { active: 0, names: [], domains: {} };

  for (let i = 0; i < users.length; i++) {
    const user = users[i];

    if (user.active) {
      result.active++;
      result.names.push(user.name.toUpperCase());

      const domain = user.email.split("@")[1];

      if (!result.domains[domain]) result.domains[domain] = 0;

      result.domains[domain]++;
    }
  }

  return result;
}

const users = [
  { name: "Ana", email: "[email protected]", active: true },
  { name: "Bo", email: "[email protected]", active: false },
  { name: "Cy", email: "[email protected]", active: true },
];

console.log(summarize(users));
Text
{ active: 2, names: [ 'ANA', 'CY' ], domains: { 'example.com': 2 } }

It works, and it does four jobs in one loop: filtering, counting, transforming names and counting domains. Each job is tangled with the others, and a change to one means reading all of the body. The refactoring pulls them apart into small pure functions that each do one thing, and then composes them.

JavaScript
const isActive = (user) => user.active;
const displayName = (user) => user.name.toUpperCase();
const domainOf = (user) => user.email.split("@")[1];

const countBy = (items, keyOf) =>
  items.reduce((counts, item) => {
    const key = keyOf(item);

    counts.set(key, (counts.get(key) ?? 0) + 1);

    return counts;
  }, new Map());

const summarizeFunctional = (users) => {
  const active = users.filter(isActive);

  return {
    active: active.length,
    names: active.map(displayName),
    domains: Object.fromEntries(countBy(active, domainOf)),
  };
};

console.log(summarizeFunctional(users));
Text
{ active: 2, names: [ 'ANA', 'CY' ], domains: { 'example.com': 2 } }

The result is identical, and the structure is different. The three small functions at the top have names that say what they decide, they can be tested one at a time and countBy can be reused for anything that needs a count by key. The summary function filters once and then derives each field from the filtered list, so each field reads on its own. The accumulator Map inside countBy is mutated, which is fine, since it is created inside the function and never escapes until it is returned complete. That is the compromise: pure from the outside, with local mutation where it is simpler and cheaper.

The test of a good refactoring is whether the next change is easier. Adding a field, such as the number of inactive users, now means adding one line to summarizeFunctional, and changing how the name is displayed means editing one small function.

Testing pure functions

Purity makes tests short, since a test is an input and an expected output, and a table of cases covers a function completely. There are no mocks, no setup and no teardown, and tests run in any order, in parallel.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

const slugify = (text) =>
  text
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");

const cases = [
  ["Hello World", "hello-world"],
  ["  Spaces  everywhere ", "spaces-everywhere"],
  ["Symbols & Things!", "symbols-things"],
  ["", ""],
];

for (const [input, expected] of cases) {
  test(`slugify(${JSON.stringify(input)})`, () => {
    assert.equal(slugify(input), expected);
  });
}
Text
✔ slugify("Hello World") (0.8ms)
✔ slugify("  Spaces  everywhere ") (0.2ms)
✔ slugify("Symbols & Things!") (0.2ms)
✔ slugify("") (0.2ms)

Adding a case is one line in the table. A bug report becomes a new row, which prevents the bug from returning. For the impure shell, test fewer things with more care: use fakes for the clock and the network, and check that the shell calls the pure core with the right inputs. The more of the program that lives in the core, the less needs such tests.

Equality, identity and change detection

Immutable data changes how you check whether something changed. If you never mutate an object, then a new object means a change, and the same object means no change, and the check is a single reference comparison with ===. This is the idea behind UI frameworks that skip re-rendering when a value is the same object, behind memoized selectors and behind cheap undo history.

JavaScript
const before = { items: [1, 2], meta: { page: 1 } };
const after = { ...before, items: [...before.items, 3] };

console.log(before === after, before.items === after.items, before.meta === after.meta);
Text
false false true

The root and the changed branch are new objects, and the meta branch is shared, so a consumer that only cares about meta can see that it did not change with one comparison. If you mutated before.items instead, before.items === after.items would be true while the contents had changed, and the consumer would miss the update. That is the main reason that frameworks that compare by reference ask you not to mutate state. When you must compare contents, JSON.stringify is a rough tool and a deep-equal helper, such as util.isDeepStrictEqual in Node.js, is the right one.

Validation that collects every error

A result object that stops at the first failure is right for a pipeline, and wrong for a form, where the user wants to see all the problems at once. The functional answer is to run every check and gather the results, with plain functions and arrays.

JavaScript
const rules = [
  (user) => (user.name ? null : "name is required"),
  (user) => (user.email?.includes("@") ? null : "email is invalid"),
  (user) => (user.age >= 18 ? null : "must be 18 or older"),
];

const validate = (user) => rules.map((rule) => rule(user)).filter((message) => message !== null);

console.log(validate({ name: "Ana", email: "[email protected]", age: 30 }));
console.log(validate({ name: "", email: "nope", age: 12 }));
Text
[]
[ 'name is required', 'email is invalid', 'must be 18 or older' ]

Each rule is a pure function from the data to a message or null, the list of rules is data, and adding a rule means adding one line. The empty array means valid. There is no exception, no shared state and no ordering between the rules, and the same list works for the browser and the server.

Functional programming and the user interface

Front-end frameworks adopted these ideas early. A React function component is meant to be a pure function from props and state to a description of the screen, and useReducer and Redux are reducers over immutable state, as shown above. Because the render does not change anything, the framework can call it as often as it likes, skip it when the inputs have not changed, and run it again after an error. Effects, such as fetching data or subscribing to events, are placed in useEffect, which is the framework's name for the thin impure shell. When you work in such a framework, the functional habits are not optional style. They are the contract: do not mutate props or state, keep render free of side effects and put the effects where the framework expects them.

A path for learning

Learn the style in small steps, and apply each to real code before moving on. First, replace loops that build arrays with map and filter, and check that the results match. Second, stop mutating function arguments, and write each function so that it returns a new value. Third, separate one feature into a pure core and an effect shell, and write table tests for the core. Fourth, write pipe yourself, and use it on a chain of three functions. Fifth, model a piece of state as a reducer and replay a list of actions through it. Sixth, read about a functional language or library, to see the ideas in a stricter setting. By then the hybrid style will feel normal, and you will have a sense of where it helps your code and where a plain loop is better.

Composing asynchronous functions

Real pipelines often include steps that return promises. A synchronous pipe cannot connect them, since each step would receive a promise and not a value. The fix is a pipe that awaits each step, which is the same function with one extra keyword.

JavaScript
const pipeAsync = (...fns) => (input) =>
  fns.reduce((promise, fn) => promise.then(fn), Promise.resolve(input));

const fetchUser = async (id) => ({ id, name: "user" + id });
const addGreeting = (user) => ({ ...user, greeting: "Hello, " + user.name });
const save = async (user) => ({ ...user, saved: true });

const process = pipeAsync(fetchUser, addGreeting, save);

console.log(await process(7));
Text
{ id: 7, name: 'user7', greeting: 'Hello, user7', saved: true }

Each step may return a plain value or a promise, since then handles both, and an error in any step rejects the whole pipeline and skips the rest, which is the failure behavior you want. Inside an async function, the same sequence is three lines with await, and is often clearer. The pipeline form is worth it when the list of steps is data, for example a list of middleware that you build at startup.

Immutability in types

TypeScript can enforce read-only data at compile time, with no runtime cost. The readonly modifier, ReadonlyArray<T> and the Readonly<T> utility type make mutation a compile error.

TypeScript
type Todo = Readonly<{ id: number; title: string; tags: readonly string[] }>;

function complete(todo: Todo): Todo {
  return { ...todo, title: todo.title + " (done)", tags: [...todo.tags, "done"] };
}

const item: Todo = { id: 1, title: "write", tags: ["draft"] };

console.log(complete(item));
Text
{ id: 1, title: 'write (done)', tags: [ 'draft', 'done' ] }

An attempt to assign todo.title = "x" or call todo.tags.push("x") fails to compile. The types disappear when the code is compiled, so there is no protection at runtime, and a frozen object in development covers that. Used together, readonly types and Object.freeze catch mutation both in the editor and when the program runs. The as const assertion makes a literal deeply read-only and narrows it to its exact values, which suits tables of constants.

Naming and documenting functional code

Small functions live or die by their names. A name should say what the function returns or decides, not how: isActive, displayName, totalOf, byCustomer. Predicates, functions that return a boolean, start with is, has or can. Functions that build something start with make, create or build, and transformations are named for the result, as in slugFrom. Avoid names that describe the mechanism, such as mapAndFilter, since they stop being true when the mechanism changes.

Write a one-line comment above any function whose contract is not obvious from its name and parameters, especially for these questions: does it change its argument, can it throw, what does it return for empty input, and is it safe to call with the same input twice. In a codebase with TypeScript, the types carry the first part. In plain JavaScript, a JSDoc comment with @param and @returns does, and the editor shows it when someone calls the function. The aim is that nobody has to read the body of a small function to know what it does, which is the promise of the style.

Reading functional code you did not write

When you meet a long pipeline in someone else's code, read it from the data outward. Find the input, then read each step as a statement of what happens to the data, and write down the shape after each one: a list of objects, a list of strings, an object keyed by name, a number. Most confusion in a chain comes from a step that changes the shape, such as reduce into an object or flatMap from nested lists to a flat one, and noting the shape at each point removes it. If a step is hard to follow, extract it into a named function and give it a test, and the pipeline becomes a list of names that explain themselves. If a reduce is hard to follow, rewrite it once as a loop with a descriptive variable name, check that the results match and keep whichever version the team finds clearer. Neither is wrong, and readability for the next person is the deciding factor.

When you debug such code, insert tap calls or temporary console.log calls between steps and compare the data against what you expect. Because each step is a pure function, you can also copy the failing input into a small script, call the steps one at a time and see which one produces the surprise. That ability to isolate a step with no setup is one of the quiet benefits of keeping logic pure, and it saves more time in a year than the style costs to learn.

Where the style costs more than it gives

Functional JavaScript has real costs, and it helps to know where they are.

Allocation. Immutable updates create new objects and arrays, and chains of map and filter create intermediate arrays. For ordinary sizes this is unnoticeable, and for hot loops over large data, it can matter, so measure before you worry, and keep a mutable local variable inside a function when it is faster and invisible to callers.

Readability for the team. Heavy use of reduce, point-free pipelines and curried helpers can be harder for colleagues to read than a plain loop. The best code is clear to the people who maintain it, and a loop that says what it does beats a clever fold.

Stack traces and debugging. Long pipelines of anonymous arrows give poor traces. Name the steps that matter, and use tap to look inside.

Language fit. JavaScript has no built-in immutable collections, no pattern matching and no tail call optimization, so some functional idioms are awkward. Libraries and TypeScript fill part of the gap.

Side effects are still needed. Programs exist to have effects. The style does not remove them. It confines them.

Libraries

You can write functional JavaScript with nothing but the language. Libraries add convenience. Ramda and Lodash's fp module provide curried, data-last utilities for pipelines. Immer makes immutable updates easy by letting you write them as mutations on a draft. fp-ts and Effect add typed Option, Either and effect abstractions for TypeScript, with a steeper learning curve and a stronger guarantee. Immutable-collection libraries provide data structures with real structural sharing. Choose by what hurts: if nested updates are the pain, use Immer, and if you want typed errors, look at the typed libraries. Do not adopt a library to replace a standard method that already does the job.

Common mistakes

Mutating inside a map callback, so that the "transformation" has side effects. Using forEach to build a new array, where map is the right tool. Using reduce with a spread in the accumulator over a large list. Passing a function with optional parameters, such as parseInt, straight to map. Writing a pipeline of functions that secretly depend on shared mutable state, so the order matters in ways that the types do not show. Returning undefined from a map callback by forgetting return in a braced arrow. Freezing an object and then mutating a nested one that is not frozen. And chasing purity so far that the code becomes harder to understand than the version that mutates a local variable.

Where this guide stops

Functional programming is a large field, and a guide on JavaScript can cover only the part that suits the language. Category theory terms such as functor and monad describe patterns that exist in JavaScript, in arrays and promises for example, and learning them is optional. Languages built for the style, such as Haskell, OCaml, Elixir and Clojure, enforce immutability and provide features that JavaScript lacks, and reading about them is a good way to learn what the habits are for. TypeScript's type system can encode many functional ideas, with its own learning curve, and the typed libraries lean on it heavily. And performance advice depends on the engine and the data, so measure.

Also inPatterns
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.