Closures are one of the most confusing concepts for new JavaScript learners. They are very powerful. Once you understand them well, your JavaScript...
For further actions, you may consider blocking this person and/or reporting abuse
Loved the article! I thought about
useStateThis 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.
Misconceptions About Closures
Jon Randy 🎖️ ・ Sep 27 '23
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.
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.