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