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

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.


It limits the object initialization costs and additionally ensures that all function invocations use the same object. This allows, for example, state to be stored in the object for future invocations to use.

While it's possible that it does limit memory usage, usually the GC will collect unused objects anyways, so this pattern is not likely to help much.

This pattern is a specific form of closure.


I'm not sure if this pattern has a more correct name, but this looks like a module to me, and the reason it is used is to both encapsulate and to maintain state.

The closure (identified by a function within a function) ensures that the inner function has access to the variables within the outer function.

In the example you gave, the inner function is returned (and assigned to foo) by executing the outer function which means tmpObject continues to live within the closure and multiple calls to the inner function foo() will operate on the same instance of tmpObject.