- If you want a mid-level understanding of closures.
- If you are curious why closure is called closure.
- You want real-life examples and not simple counter or greeting examples. This article links to the more interesting and real closures demos from around the web.
- Closures keeps your code DRY (Don’t Repeat Yourself) through the ability to create similar but unique functions based on the same foundational code.
- React Hooks and functional components use them. Understand closures to understand these two prior ideas.
- Reduce boilerplate code used to communicate temporary values.
StackOverflow thread has several examples showing clearer use cases beyond the MDN or W3C School examples.
The term dates back to 1964 to indicate variables and functions (e.g. anonymous functions/ lambda expressions/function literal/lambda abstraction, which are all synonyms of each other btw, as well as named functions) are bound/scoped/limited to the lexical environment of its creation.
Lexical environment vs scope? They are related but different. Check this StackOverflow for a concrete explanation of the two. For now, a lexical environment knows/has access to its parent lexical environment and any other parents in the direct chain/stack.
So a closure “encloses/wraps” a function (1 or more inner functions) to a parent lexical environment.
This enclosed function is able to execute code while having access to variables in the parent function (the variables are declared in the parent and not in the inner/enclosed function).
Note: Access to the parent function variables is by reference to the variable’s location in memory and is not a copy of the variable’s value. As such you can modify the parent variable value(s).
Have thoughts on closures (regardless of the language)? Drop note. I'd love to hear and see your examples, explanations, and other details that can clarify the how/why/when.