I first learned about closures before starting my coding bootcamp and thought I had a general handle on the concept. Then I learned about them for a second time in my course and felt more confused than I was before. I decided to write a post to solidify my understanding of the subject (third time’s a charm, I guess?). The thing is – closures aren’t as complicated as they seem and they allow you to write some cool, creative, and efficient code. I think the key to understanding closures is to practice with examples and play around with the code until you have a good idea of what is going to return and why. This is good practice for understanding all coding concepts, but I think many explanations of closures have these lofty, conceptual descriptions that are confusing and make everything seem more complicated than it actually is.
What Are Closures?
To summarize, a closure has three scope chains. It has access to:
- Its own scope (the inner function’s variables)
- The outer function’s variables and parameters
- Global variables (window environment)
Here is a simple example of a closure:
Here’s what’s happening:
We can see the inner function’s scope:
And the outer function’s scope:
And the global scope!:
Now what happens when we add a variable to the inner function?
How Does This Work?
The inner function also has access to the outer function’s parameters, however, the inner function cannot access the outer function’s arguments object. It can only access the outer function’s parameters directly. (The arguments object is an array-like object corresponding to the arguments passed to a function. Each scope can only have one arguments object. Read more about arguments object here.) Along the same lines, closures store references to the outer function’s variables, but they do not store actual values.
The language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.
Why Are Closures Necessary?
1. A scope is mostly created at the function level (more on that below). They aren’t created by while/for loops or by if statements, like other languages. Closures provide us with more access and functionality.
A Quick Note On Scopes