DEV Community

Cover image for Misconceptions About Closures
Jon Randy 🎖️
Jon Randy 🎖️

Posted on • Updated on

Misconceptions About Closures

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:

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

Top comments (5)

jamesthomson profile image
James Thomson

Personally, waaay back when, I found this really drove that home.

const myVar = 'foo'

  const myVar = 'bar'

Enter fullscreen mode Exit fullscreen mode

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 using const/let it's quite clear.

tanmaycode profile image
Tanmay Agrawal

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

grigorkh profile image
Grigor Khachatryan

Nice article!

dsaga profile image
Dusan Petkovic

Good as a refresher thanks!

Do other languages use a similar concept of closures?

tanmaycode profile image
Tanmay Agrawal

Debugging the closure in the right way