Closures

Closures are an essential part of JavaScript that, for me at least, are easy to understand but tricky to explain well. Unfortunately, they come up a lot in job interviews, so I thought it was time to take a deeper dive into what closures are and why they are important.

What Are They?

According to MDN, a closure is the combination of a function and the lexical environment within which that function was declared.

What does that mean? When you declare a function inside of another function, the inner function has access to its own scope, as well as the scope of the outer function. In other words, the inner function will still have access to any local variables that were in-scope at the time of creation, even though those variables may not be in scope when that function is called.

How Do You Use Them?

To use a closure, all you have to do is define a function within another function and then return it, or pass it as an argument to another function so that it can be used outside of the context it where it was defined.

What Are They Good For?

Closures allow us to do a lot of handy things. Here are a few examples:

Data Privacy

Data Privacy. Closures are one of the primary ways to make data private in JavaScript. When you use a closure to wrap a variable, that variable is only accessible inside the outer function. The only way to access that data from somewhere else in your code is by creating a function inside the outer function that has access.

Because myData is created inside a closure, it can’t be manipulated from outside of outerFunction(). The only way it is accessible is through the inner function.

State

State. Closures are essential for creating objects that have state. Just like in the private data example above, if we create a variable in the outer function we can manipulate it with inner functions and use it to keep track of the state of an object.

In the example above, we create a simple counter that uses a variable called state to keep track of what number we are on. In this case the outer function returns an object with three functions in it that allow us to manipulate the state of our counter in different ways.

Factory Functions

Factory Functions. Another useful aspect of closures is how they can be used to create factory functions. A factory function is a function that returns other functions.

In this case, we’ve used a closure to create a function that outputs a bunch of new functions with variations based on the argument we pass to the factory function. This allows us to create a bunch of functions dynamically with just a few lines of code.

So closures can be pretty magical and it turns out…. Understanding them allows you to do some extremely powerful things.