DEV Community

Discussion on: What is Closure in JavaScript?

Collapse
 
pentacular profile image
pentacular

Closure is when a function remembers and continues to access variables from outside its scope, even when the function is executed in a different scope.

This is somewhat incorrect.

A lexical closure can only form over variables in scope at that point.

let a = 1;
const foo = () => a;

a is in scope in the body of foo, but it is not a bound variable of the function foo -- it is a free variable.

A function with a free variable is an open expression, and can't be understood on its own.

To close the function, we capture (and share) the free variable, which binds it, and call the result a closure.

It also doesn't really make sense to talk about executing a function in a scope -- scope is a lexical property of the program, not a dynamic property of execution.

The point of producing a closed function is that it doesn't execute in a scope -- it has all of the things it requires bound already, so it just executes in the global environment like any other function.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

You could pass foo to any other function and it would still return 1, even when a goes out of scope; how is that not a closure?

Collapse
 
pentacular profile image
pentacular

Even when a goes out of the scope of what? :)