Skip to content

JavaScript Patterns That Stayed: Modules, Higher-Order Functions, Currying

Three JavaScript patterns have survived every framework change: the module pattern for clean encapsulation, higher-order functions for functions as values and currying for specialized variants. Why they form the foundation of modern utility libraries.

≈ 10 min readSoftwareFrontend

A pattern is not a library and not a framework feature. It is the shape in which code is arranged – and that sits one level below whatever framework currently sits on top. For us, only a few years lay between jQuery, Backbone, Angular 1, Angular 2 and React. The tools were swapped out; the arrangement underneath stayed remarkably constant.

I pick out three of these arrangements here: the module pattern, higher-order functions and currying or partial application. They build on each other, and once you have taken them apart, you read modern JavaScript code with different eyes. I assume ES2015 as the baseline.

The three patterns in one sentence each:

  • The module pattern encapsulates state and exposes only a deliberately chosen public API.
  • Higher-Order Functions treat functions as values – they take functions as arguments or return them.
  • Currying and partial application turn a generic function into specialized, preconfigured variants.

Module pattern: two routes, one goal#

The oldest problem in browser JavaScript is the global namespace. In the past, every variable you did not deliberately encapsulate ended up on the window object, and two scripts could overwrite each other without noticing. The solution before ES6 was a convention, not a language feature: the Immediately Invoked Function Expression, IIFE for short. You wrap code in a function, call it immediately and use the resulting scope as a private space. What is declared inside stays inside – unless you deliberately return it as an object. This return of the public API is also called the Revealing Module Pattern.

const counterModule = (function () {
  let count = 0; // private, not accessible from outside

  return {
    increment() {
      return ++count;
    },
    get() {
      return count;
    }
  };
})();

counterModule.increment(); // 1
counterModule.increment(); // 2
counterModule.get();       // 2
counterModule.count;       // undefined – deliberately not exposed

The trick lies in the closure: the returned methods keep access to count even though the outer function finished long ago. From the outside, there is no way to set count directly. That is exactly what we wanted – encapsulation without language support, purely through scope and closure.

Since ES2015, there are real modules in the language. Every file is its own module scope, nothing leaks to global automatically, and what should be visible from the outside you mark with export. Importing happens statically with import. The same example as an ES module:

// counter.js
let count = 0; // module-private, only visible in this file

export function increment() {
  return ++count;
}

export function get() {
  return count;
}
// app.js
import { increment, get } from './counter.js';

increment(); // 1
increment(); // 2
get();       // 2

Both pursue the same goal: private state and a clearly defined public API. The difference is the semantics. With the IIFE, encapsulation is a runtime construct based on functions and closures. With the ES module, it is part of the module system – tools can analyze the imports before execution and remove unused code. Imported bindings are also live and cannot be reassigned by the importer. Modules run implicitly in strict mode.

graph LR
  A[IIFE + Closure] --> C[Encapsulation<br/>private state<br/>clear public API]
  B[ES6 import/export] --> C

An honest word about the state of things in 2017: Node.js does not yet support native ES modules in a stable way. There you still write CommonJS with require and module.exports; the experimental --experimental-modules flag has only just appeared with Node 8.5.0. In browsers, support is fresh – Chrome 61 and Safari 10.1 already handle type="module", Firefox and Edge still behind a flag. In practice, in 2017 we therefore bundle with webpack or Rollup and let Babel translate the import/export syntax. That does not change the pattern: we think in modules, even if deployment still goes through a bundler.

Higher-Order Functions: functions are values#

The second building block is JavaScript’s real strength, and most of us used it long before we had a name for it. In JavaScript, functions are first-class values: you can store them in variables, pass them as arguments and return them from other functions. A function that takes a function as an argument or returns a function is called a higher-order function.

The best-known examples are the array methods map, filter and reduce. They have been available everywhere since ES5 (2009) and replace imperative loops with declarative transformations. Instead of describing how to iterate, you describe what happens to each element:

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);        // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15

Each of these methods is itself a higher-order function because it takes a callback. map calls the callback for each element and collects the return values in a new array. filter keeps only the elements for which the callback returns true. reduce folds the array into a single value by carrying an accumulator through all elements.

The other half of the pattern – functions that return functions – is the key to everything that comes after. A function that produces a configured function is sometimes called a function factory:

const multiplyBy = factor => n => n * factor;

const double = multiplyBy(2);
const triple = multiplyBy(3);

double(5); // 10
triple(5); // 15

[1, 2, 3].map(double); // [2, 4, 6]

multiplyBy(2) does not return a number but a new function that has remembered factor via closure. double and triple are specialized tools built from a single generic function. And because they are perfectly normal functions, you can pass them directly to map. This is exactly where higher-order functions interlock with the next pattern.

Currying and partial application: from generic to specific#

Currying means turning a function with several arguments into a chain of unary functions. f(a, b, c) becomes f(a)(b)(c). Each call takes exactly one argument and returns a function that waits for the next one – until all arguments are there and the result is computed. Again, this is implemented via closures.

const add = (a, b) => a + b;          // ordinary, two arguments at once
const curriedAdd = a => b => a + b;   // curried, unary chain

curriedAdd(10)(5); // 15

const add10 = curriedAdd(10); // specialized function, waits for b
add10(5);  // 15
add10(90); // 100

Closely related, but not the same, is partial application. Here you fix some arguments of a function and get a new function with fewer parameters. The difference from currying: partial application does not force you into unary chains but simply fixes a few arguments up front. In JavaScript, you can get this without any helpers of your own via Function.prototype.bind, which has also been available since ES5:

const add = (a, b) => a + b;

// bind fixes this (here null) and the leading arguments
const add10 = add.bind(null, 10);

add10(5);  // 15
add10(90); // 100

The benefit shows as soon as you compose such specialized functions. From a small stock of generic building blocks, you build tailored variants and plug them together. An example that shows how naturally such a building block fits into the array methods – add10 from the bind step goes straight into map:

const numbers = [1, 2, 3, 4];

const shifted = numbers.map(add10);                   // [11, 12, 13, 14]
const total = shifted.reduce((sum, n) => sum + n, 0); // 50

The arc from generic to specialized function reads well as a flow:

graph LR
  A["add(a, b)<br/>generic, two arguments"] --> B["curriedAdd(10)<br/>or add.bind(null, 10)"]
  B --> C["add10(n)<br/>specialized, one argument"]

And that is exactly why these patterns have stayed for years: they are the foundation of modern utility libraries. Ramda (since 2013) and lodash/fp ship many functions curried and with a “data-last” signature – the data comes last so that you can fix the configuration up front and conveniently compose the resulting building blocks. Once you understand the principle behind multiplyBy and curriedAdd, you also understand why these libraries are built the way they are.

Three pitfalls I see again and again#

As elegant as the patterns are, teams reliably stumble over the same spots. I want to name three of them because they get expensive in real codebases.

The first concerns the this binding with higher-order functions. If you pass an object method directly as a callback, the receiver is lost. The method is called without its object, and this is then undefined or the global object:

const counter = {
  count: 0,
  increment() {
    this.count += 1; // this depends on HOW it is called
  }
};

[1, 2, 3].forEach(counter.increment);
// TypeError, i.e. counter.count stays 0 – this is not counter

The solution in 2017 is clear-cut. You bind this with bind, wrap the call in an arrow function that takes its this lexically from the surrounding context, or use the thisArg parameter that map, filter and forEach offer as a second argument:

[1, 2, 3].forEach(counter.increment.bind(counter));
[1, 2, 3].forEach(() => counter.increment());
[1, 2, 3].forEach(counter.increment, counter); // thisArg

Arrow functions are the sharpest tool here because they do not bring their own this at all – they inherit it from the surrounding scope. In many cases, that makes this class of error disappear entirely.

The second pitfall is overusing currying. Deeply nested f(a)(b)(c)(d) chains look neat in a blog post, but in team code they cost readability. They are harder to debug, the stack traces become confusing, and whoever reads the code six months later has to unfold the chain in their head again. Currying pays off where specialization or composition brings a concrete advantage. Where it only looks functional, it costs more than it brings.

The third concerns reduce without an initial value. If you leave out the initialValue argument, reduce takes the first array element as the initial value – and throws a TypeError on an empty array. On top of that, the semantics of the accumulator are then tied to the element type, which quickly leads to subtle bugs:

[].reduce((sum, n) => sum + n);    // TypeError: Reduce of empty array
[].reduce((sum, n) => sum + n, 0); // 0 – correct, because initial value set

For sums, building lists and other folds with a neutral element, I therefore set the initial value explicitly. Where there is no neutral element in domain terms, I prefer to handle the empty case deliberately instead of inventing an artificial initial value.

Conclusion#

When I put the three patterns side by side, a common line stands out. The module pattern encapsulates state, whether via IIFE and closure or via ES module – the goal stays the same, only the level moves from convention into the language. Higher-order functions turn functions into values and replace loops with transformations. Currying and partial application build specialized variants from Generic Functions that can be composed. The syntax shifted between ES5 and ES6; the principle behind it did not.

That is exactly what I have learned over the years: patterns beat syntax. The language features will keep changing – years lie between the first IIFE and today’s import – but encapsulation, functions as values and specialization through preconfiguration have stayed stable. If you master this core, you do not have to start from scratch at the next framework change. You recognize the old acquaintances in new clothes, and in the long run that is worth more than any current library version.

Further reading#

Revised and translated from German with the help of AI.