Misconceptions About Closures

Jon Randy πŸŽ–οΈ - Sep 27 '23 - - Dev Community

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:

  1. Closures are not functions
  2. 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.

As a simplified visual:
Closure

*Except for functions created with new Function(...) which form closures with the global scope

. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player