The two biggest (and unfortunately widespread) misconceptions about closures:
A closure is a special type of function that has access to its surrounding scope β
This is entirely wrong for two reasons:
- Closures are not functions
- ALL functions have access to their surrounding (lexical) scope*
To create a closure, you need to nest functions β
Again, entirely wrong - nesting of functions is irrelevant! Whenever a function is created, an associated closure is also created.
So, what is a closure?
From MDN:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state
The closure allows the function to access the state in which it was created.
*Except for functions created with new Function(...)
which form closures with the global scope
Top comments (10)
Personally, waaay back when, I found this really drove that home.
It blew my mind that a block statement could be used like this.
Of course, we were dealing with
var
which had different implications depending on strict mode, but when usingconst
/let
it's quite clear.This i realized when I was reading about the difference between the var, let and const. The example was given in same as the above. I though wait! whats happening there
One of the interesting implications of this is that most of the times when we say "function" in JavaScript, we are actually talking about a closure.
Functions cannot be defined, assigned to variables, passed as arguments or returned. Functions are handled internally by the language and referenced in some way by closures.
But this isn't really practical from a language perspective, so we have instead started using "function" to mean closure as well as an actualΒ function. This works well most of the time, but leads to some insignificant misconceptions about terminology.
Looking at it from a communication perspective:
Every "function" is actually a closure in JS.Β The function/closure distinction is, in practice, entirely useless.
Meanwhile, "closure that captures values" vs. "closure that doesn't capture values" is a way more interesting distinction, yet needs a lot more words to express. Calling one of themΒ "function" and the other "closure", while technically incorrect, makes it a lot easier to communicate those ideas. In the same way, saying "use a closure" is a lot simpler thanΒ "make use of the fact that javascript functions are actually closures"
Good as a refresher thanks!
Do other languages use a similar concept of closures?
Many scripting languages have features like this.
Lua functions work almost the exact same way (even the misnomer). Ruby has lambdas, which also capture their surrounding scope. Many functional languages have closures and make heavy use of them.
This is all very true. Informative, too. Thanks for posting!
Nice article
Nice article!
Debugging the closure in the right way
Thanks for this hint of misconceptions!