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 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 (5)
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
Nice article!
Good as a refresher thanks!
Do other languages use a similar concept of closures?
Debugging the closure in the right way