Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 156 ยท Functions

Functional Programming Patterns

Learn practical functional programming in JavaScript - pure functions, immutable updates, IIFEs, currying, partial application, pipe and memoization.

Functional programming is a style of writing code where you build programs out of small functions that take input and return output, without quietly changing things around them. JavaScript isn't a "pure" functional language, but it has everything the style needs: functions are values, closures remember data, and arrays come with map, filter and reduce.

You don't have to adopt the whole philosophy to benefit from it. A handful of patterns (pure functions, immutable updates, currying, composition and memoization) make code easier to test, easier to reuse and much easier to reason about. This lesson walks through each one with examples you can run and change.

Pure functions

A function is pure when it follows two rules:

  1. Same input, same output. Given the same arguments, it always returns the same result. It doesn't depend on the clock, random numbers, global variables or anything else that can change between calls.
  2. No side effects. It doesn't change anything outside itself: no editing its arguments, no writing to globals, no logging, no network calls, no DOM changes.
JS Pure vs impure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pure functions are a joy to test: call them with some input and check the output. There is no setup, no mocking and no "it depends what ran before". They are also safe to call in any order, cache or run again.

Of course, a program that has no side effects does nothing useful. It can't show anything or save anything. The practical goal is to keep the core logic pure and push side effects (DOM updates, fetch, logging, storage) to the edges of your program, in a few clearly marked places.

Immutability: update by copying

Immutable data is never changed after it's created. Instead of editing an object or array, you create a new one with the change applied. The spread syntax and the non-mutating array methods make this short to write:

Instead of (mutates) Write (returns a new value)
arr.push(x) [...arr, x]
arr.splice(i, 1) arr.filter((_, j) => j !== i) or arr.toSpliced(i, 1)
arr[i] = x arr.with(i, x)
arr.sort() arr.toSorted()
arr.reverse() arr.toReversed()
obj.key = value { ...obj, key: value }
delete obj.key const { key, ...rest } = obj

toSorted(), toReversed(), toSpliced() and with() arrived in ES2023 and work in all current browsers.

JS Updating state without mutation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the last line: the second todo didn't change, so both states share the very same object. Copying only the parts along the path you changed is called structural sharing, and it keeps immutable updates cheap. It's also why UI libraries can detect changes quickly: if oldState.todos !== newState.todos, something in the list changed.

Object.freeze() makes an object read-only, but only one level deep. The next lesson, Property Descriptors and Object Protection, shows how to freeze deeply. For copying in general, see Copying Objects.

IIFE: run a function right away

An IIFE (immediately invoked function expression, said "iffy") is a function that's defined and called in one step. The surrounding parentheses turn the declaration into an expression, and the final () calls it:

JavaScript
(function () {
  const secret = "only visible in here";
  console.log("runs once, immediately");
})();

// Arrow version
(() => {
  // ...
})();

Before let, const and modules, an IIFE was the main way to create a private scope so variables didn't leak into the global object. Today, modules and block scope do that job, so you mostly see IIFEs in older code. One modern use remains: computing a value with several steps, keeping the helper variables tidy.

JS An IIFE that computes a value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Currying and partial application

Partial application means fixing some of a function's arguments now and supplying the rest later. You get back a new, more specific function. You already met one built-in way to do it: bind() from call, apply and bind. A small helper works for any function:

JavaScript
function partial(fn, ...preset) {
  return (...later) => fn(...preset, ...later);
}

const greet = (greeting, name) => `${greeting}, ${name}!`;
const sayHi = partial(greet, "Hi");
sayHi("Ana"); // "Hi, Ana!"

Currying goes one step further: it turns a function of several arguments into a chain of functions that each take one argument. add(a, b, c) becomes add(a)(b)(c). Arrow functions make hand-written curried functions very short:

JS Curried functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The curry helper relies on fn.length, the number of declared parameters. That number ignores rest parameters and anything after the first default value, so curry functions with plain, fixed parameter lists.

Why bother? Curried and partially applied functions slot neatly into array methods and pipelines, which expect one-argument callbacks. filter(isValidPercent) reads like a sentence. Put the arguments that change least (configuration) first and the data last, so the data can flow in at the end.

Don't curry everything. Currying shines for small, reusable predicates and formatters. For a function with many options, an options object (format(amount, { currency, decimals })) is usually clearer to the next person who reads it.

Composition and pipe

Composition builds a new function by chaining existing ones: the output of one becomes the input of the next. In Higher-Order Functions you wrote a small pipe(). Here are both directions, side by side:

  • pipe(f, g, h)(x) runs left to right: h(g(f(x))).
  • compose(f, g, h)(x) runs right to left: f(g(h(x))), matching how math writes it.
JS Building a pipeline from small functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each step is tiny and easy to test alone, and the pipeline reads like a list of instructions. A proposed pipe operator (|>) would make this built-in syntax one day, but it is still an early-stage proposal, so use a helper for now.

Memoization

A pure function always returns the same output for the same input, so you can safely remember results and skip the work next time. That's memoization. Recursion used it to speed up Fibonacci; here is a reusable wrapper:

JS A memoize helper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Some rules for using it well:

  • Only memoize pure functions. If the result depends on the time or on outside data, the cache will return stale answers.
  • Think about the key. This version handles one primitive argument. For several arguments you need a key such as JSON.stringify(args), which has costs and edge cases of its own. Objects as keys are compared by identity, not content.
  • Caches grow. A Map keeps every entry forever. For object keys, a WeakMap lets entries disappear when the object does; for long-running apps, limit the size or clear the cache.

Putting it together

Functional patterns work best in combination, and in moderation. A typical modern codebase uses:

  • pure functions for business rules (prices, validation, formatting),
  • immutable updates for application state,
  • map, filter and reduce instead of hand-written loops that push into arrays,
  • small composed helpers for data cleanup,
  • and plain, clearly marked imperative code for the side effects: DOM, network and storage.

That mix keeps the risky parts small and the bulk of your logic predictable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function is pure?

    Math.max(a, b) depends only on its inputs and changes nothing. sort() mutates its argument, Math.random() gives different results, and console.log is a side effect.
  2. 2. What does between(1)(10)(5) return for const between = (min) => (max) => (value) => value >= min && value <= max?

    Each call supplies one argument. After all three, the innermost function runs and checks that 5 is between 1 and 10.
  3. 3. In which order does pipe(a, b, c)(x) call the functions?

    pipe runs left to right, passing each result to the next function: c(b(a(x))).
  4. 4. Which immutable replacement for arr.sort() leaves arr unchanged?

    toSorted() returns a new sorted array. sort().slice() still sorts the original first, and sorting a frozen array throws.
  5. 5. Why is memoization only safe for pure functions?

    The cache assumes the same input always gives the same output. If the function depends on changing data or does side effects, reusing old results is wrong.

Summary

  • Pure functions return the same output for the same input and have no side effects; keep side effects at the edges of your program.
  • Immutable updates create new objects and arrays (...spread, map, toSorted(), with()) and share the unchanged parts.
  • An IIFE runs a function immediately; modules and block scope have replaced most of its old uses.
  • Partial application presets some arguments; currying turns a function into a chain of one-argument functions.
  • pipe and compose build bigger functions from small ones; memoization caches the results of pure functions.

Next: Objects โ€” creating and working with JavaScript's most important data structure.