Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 5, 2020 04:15 am GMT

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 (Dont 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 variables location in memory and is not a copy of the variables 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.


Original Link: https://dev.to/brad_beggs/closures-in-js-for-beyond-beginners-8ol

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To