DEV Community

Cover image for Closures (in JS) for Beyond Beginners
Brad Beggs
Brad Beggs

Posted on

Closures (in JS) for Beyond Beginners

Who is this for?

  • 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.

Why do we care about closures?

  • 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.

Real Examples and Demos

A fetch request with closure

A shopping cart example on jsfiddle

A visual analogy of closure and the holidays

StackOverflow thread has several examples showing clearer use cases beyond the MDN or W3C School examples.

Why is it called closure?

Whether it is Javascript, (or Python, Rust, Lisp, etc….) many languages have closures.

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).

References & Suggested Articles of the 31 articles I read

Wikipedia history of closures

Demystifying Javascript Closures Callbacks & iifes/

Closures in javascript in simple terms and real-life examples

Feedback

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.

Top comments (2)

Collapse
 
patricktingen profile image
Patrick Tingen

Good explanation, I did not know them ( don't program in js) but I understand it. In a way you can compare it to a singleton object as I understand it

Collapse
 
rsanchezp profile image
Raúl Sánchez

Nice and concise! Thanks.