← Back to JavaScript, page 7

javascript-0127 · Easy fresher

What are the core ideas of functional programming in JavaScript, such as pure functions, immutability, and higher-order functions?

Functional programming builds programs from small pure functions, which return the same output for the same input and cause no side effects, on immutable data, combined with higher-order functions and composition. It makes code easier to test and reason about. JavaScript supports it because functions are first-class values, though it does not enforce purity or immutability.

Full answer

Functional programming (FP) is a style, not a library. JavaScript is multi-paradigm, so you can mix it with object-oriented code.

Pure functions: the output depends only on the arguments, and the function changes nothing outside itself. Reading the current time, random numbers, a global variable, or writing to the DOM, a file, or the console makes a function impure. Pure functions are easy to test (no setup), safe to cache (memoize), and safe to run in any order. An expression that can be replaced by its value without changing the program has referential transparency.

Side effects are still needed, because programs must read input and write output. The FP approach is to keep them at the edges and keep the core logic pure.

Immutability: do not change data in place. Create new values: spread for objects and arrays, map, filter, and toSorted instead of push and sort. This avoids bugs where a shared object is changed by distant code, and it makes change detection cheap, because a new reference means a change (the base of React state updates). Object.freeze can enforce it shallowly.

First-class and higher-order functions: functions can be stored in variables, passed to other functions, and returned from them. map, filter, and reduce are higher-order functions that replace loops with intent.

Composition: build bigger behavior by chaining small functions, with pipe(f, g, h)(x) meaning h(g(f(x))). Currying and partial application make functions easier to compose.

Declarative style: say what you want (users.filter(isActive).map(getName)), not how to loop.

Trade-offs: creating new objects costs memory and time (usually small), deep pipelines can be harder to debug, and too much cleverness reduces readability. In practice, use FP where it helps: pure helpers, immutable updates, and array pipelines.

javascript
// impure: reads and changes outside state
let total = 0;
function addToTotalImpure(n) {
  total += n;
  return total;
}
console.log(addToTotalImpure(5), addToTotalImpure(5));

// pure: depends only on its arguments
const add = (a, b) => a + b;
console.log(add(5, 5), add(5, 5));

// mutation versus a new value
const cart = Object.freeze([{ name: 'pen', price: 2 }, { name: 'book', price: 12 }]);
const withItem = [...cart, { name: 'bag', price: 30 }];
console.log(cart.length, withItem.length, cart === withItem);
try {
  cart.push({ name: 'x', price: 1 });
} catch (error) {
  console.log('frozen array push:', error.name);
}

// higher-order functions and pipelines
const users = [
  { name: 'Asha', active: true, age: 31 },
  { name: 'Ben', active: false, age: 25 },
  { name: 'Chen', active: true, age: 42 },
];
const isActive = (user) => user.active;
const getName = (user) => user.name;
console.log(users.filter(isActive).map(getName));
console.log(users.reduce((sum, user) => sum + user.age, 0) / users.length);

// composition
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const slugify = pipe(
  (text) => text.trim(),
  (text) => text.toLowerCase(),
  (text) => text.replace(/[^a-z0-9]+/g, '-'),
  (text) => text.replace(/^-|-$/g, ''),
);
console.log(slugify('  Hello, Functional World!  '));

// immutable update of a nested object
const state = { user: { name: 'Asha', tags: ['a'] }, count: 1 };
const next = { ...state, user: { ...state.user, tags: [...state.user.tags, 'b'] } };
console.log(state.user.tags, next.user.tags, state.count === next.count, state.user === next.user);

// sorting without changing the original
const scores = [30, 5, 100];
console.log(scores.toSorted((a, b) => a - b), scores);

Run with Node.js v24.22.1 as js-127.js; two runs gave identical output. Output: 5 10 10 10 2 3 false frozen array push: TypeError [ 'Asha', 'Chen' ] 32.666666666666664 hello-functional-world [ 'a' ] [ 'a', 'b' ] true false [ 5, 30, 100 ] [ 30, 5, 100 ]

Key points

  • Pure function: same input gives same output, with no side effects; easy to test and cache.
  • Keep side effects at the edges and the core logic pure.
  • Immutability: create new values with spread, map, filter, and toSorted instead of changing data.
  • Higher-order functions and composition build behavior from small pieces.
  • JavaScript allows FP but does not enforce it; balance purity with readability.

Common mistakes

  • Calling a function pure while it reads the date, random values, or global state.
  • Believing that const or Object.freeze make nested data deeply immutable.
  • Mutating inputs with sort, reverse, or splice inside "pure" functions.
  • Chaining very long pipelines with no names, which hurts readability and debugging.

Follow-ups

  • Why does immutability make change detection cheap in UI libraries?
  • What is referential transparency, and how does it help with memoization?
  • Where would you still use mutation for performance, and how would you contain it?

Tips

  • Define pure function with an example and a counterexample.
  • Say that side effects are pushed to the edges of the program.
  • Mention the trade-offs, so the answer does not sound like a sales pitch.