DEV Community

Cover image for Mastering closures in JavaScript

Mastering closures in JavaScript

Taha Shashtari on March 20, 2024

Closures are one of the most confusing concepts for new JavaScript learners. They are very powerful. Once you understand them well, your JavaScript...
Collapse
 
patzi275 profile image
Patrick Zocli

Loved the article! I thought about useState

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

A closure is a function that uses and retains access to a variable defined outside of its scope.

This is not correct. A closure is not a function, and you don't have to do anything special to create one. Every function has an associated closure, which is created automatically.

Collapse
 
tahazsh profile image
Taha Shashtari

You're correct; if we need to be more semantically correct, a closure is a record storing a function together with an environment. But my definition here is to make it simpler to understand from a practical point of view.

Collapse
 
jonrandy profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Jon Randy 🎖️ • Edited

I just don't think giving people an incorrect definition of what something is and how it is created is helpful to them to gain a fuller understanding of the language they're working with.

You've done mostly a good job of explaining what goes on, but fall down towards the end. I don't see that telling people the truth that all functions have an associated closure, which is created automatically really makes anything more difficult to understand. You could then go on - as you have - to explain how these closures can be useful.

If a closure actually was 'a function that remembers its surrounding state', then there would be no point having two different words for 'closure' and 'function' since ALL functions have this capability.

Knowing that all functions have an associated closure is also helpful in understanding why functions can access global variables, module level functions can access module level variables etc. By giving the incorrect or 'simplified' definition, further insights or realisations such as these become less likely - making JS seem more opaque than it actually is.

In my opinion, teaching the definition of closures in this way is a disservice to learners.