DEV Community

Discussion on: Closures: A Powerful Concept in JavaScript

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You might want to consider re-wording this:

A closure is a function that has access to variables from its outer lexical scope...

ALL functions have access to variables from their outer lexical scope. A closure and a function are two different things. From MDN:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

The distinction is slight, but saying that a closure is a function just generates the incorrect perception that a closure is some kind of special type of function - which is not the case at all. I'm not sure where this misunderstanding comes from - maybe a lot of JS courses are teaching it weirdly?

Also, you have a glaring typo in the header image 😱

Collapse
 
koushikmaratha profile image
koushikmaratha

Hi, @jonrandy

The statement "a closure is not a function" is true in the sense that a closure is not a standalone entity that can be invoked like a function. Rather, a closure is a behavior that arises from the way functions access variables from their outer lexical scope.

So, When a function accesses a variable from its outer scope, a reference to that variable is stored in the function's closure. This allows the function to maintain access to the variable even after the outer scope has been destroyed. In essence, a closure is a way for a function to "remember" the state of its outer scope at the time it was created.

Therefore, while a closure is not a standalone function, it is a behavior that is closely tied to the way functions work and their access to variables in their outer lexical scope.