What is this JavaScript pattern called and why is it used?

Your assumptions are almost correct. Let’s review those first.

  1. It assigns the return of a self-executing function

This is called an Immediately-invoked function expression or IIFE

  1. It defines a local variable within this function

This is the way of having private object fields in JavaScript as it does not provide the private keyword or functionality otherwise.

  1. It returns the actual function containing logic that makes use of the local variable.

Again, the main point is that this local variable is private.

Is there a name for this pattern?

AFAIK you can call this pattern Module Pattern. Quoting:

The Module pattern encapsulates “privacy”, state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer’s interface. With this pattern, only a public API is returned, keeping everything else within the closure private.

Comparing those two examples, my best guesses about why the first one is used are:

  1. It is implementing the Singleton design pattern.
  2. One can control the way an object of a specific type can be created using the first example. One close match with this point can be static factory methods as described in Effective Java.
  3. It’s efficient if you need the same object state every time.

But if you just need the vanilla object every time, then this pattern will probably not add any value.

Leave a Comment