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:
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. 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. 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.