If you are working with JavaScript it is critical that you understand the definition of a closure. Closures are widely employed in JavaScript code, for example:

  • as callback functions
  • for information hiding
  • in currying or partial application

As a result, without a firm grasp of how closures work you will struggle to produce high quality JavaScript code.

A definition

The most concise definition of a closure I’m aware of is by Eric Elliot. He defines a closure as:

“…the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).”

Eric Elliot – Master the JavaScript Interview: What is a Closure?

In other words, an inner function has access to the scope (state) of any outer function.

Use Cases

Let’s explore some common use cases for closures.

Information Hiding with the Module Pattern

The following is an example of a “module” pattern in JavaScript.

const sayModule = (function(msg) {
	return { 
		say: () => {
			return msg;
		}
	}
})("hello closures"); // IIFE immediately returns

sayModule.say(); 
// "hello closures"

In the above example, the IIFE (Immediately Invoked Function Expression) immediately returns the object with the method say.

return { 
	say: () => {
		return msg; // has access to msg via the closure
	}
}

The sole purpose of this function is to return the value of the msg parameter. You will note that the msg “hello closures” was passed to the IIFE at the point where we immediately invoked it.

Now when we call the modules say method, it still has access to the value of msg even though the IIFE has already returned (remember IIFE’s are immediately invoked). We can say that the inner function say has closed around the msg variable.

This is a trivial example, but it becomes extremely powerful when you want to avoid exposing too much data to consumers of your code. This is part of the fundamental principle of programming to an interface as it allows us to choose which properties/methods we want to expose as our code’s public “API”.

Partial Application

Another use case for Closures is in Partial Application, a technique often employed as part of a Functional Programming approach.

When a function is called we say it has been “applied” to its arguments. It follows, therefore, that to partially apply a function is to only apply a function to some of its arguments. This allows us to pass a subset of a given function’s arguments and receive another function which is preconfigured and ready to receive the remaining arguments. To achieve this we return an inner function from the main function which closes around the arguments of the original function. An example may help here:

const msgCombine = (arg1) => {
  return function(arg2) { // returning a function expecting remaining argument
    return `${arg1} ${arg2}`; // closure has access to arg1 even though msgCombine has returned
  };
}

// Preconfigure with first msg as "hello"
const hello = msgCombine("hello");

hello("world"); 
// "hello world"

hello("dave!");
// "hello dave!"

The important thing to note is that when calling the inner function, it still has access to the variable arg1 from the outer msgCombine function even though that function has already returned.

More Information

Closures are an extremely powerful feature in JavaScript and learning to master them will greatly improve your ability to write high-quality code. For more on this topic I strongly recommend spending the time to read the following articles in-depth:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.