DEV Community

Lukas Polak
Lukas Polak

Posted on • Updated on • Originally published at


JavaScript closures

The closure is a function that remembers the variables from the place where it was defined, regardless of where it will be executed later. In other words, a closure is a function bundled with its lexical scope. Callbacks, event handlers, higher-order functions can access variables from the outer scope thanks to that. The closure is created at runtime during the function creation, and the JavaScript engine needs to keep the variable from the outer function available until the inner function has been called. In some cases, closures can be referred as a "nested functions" or "ghost"/"memory" of the past function calls.

Function from the inner scope has access to variables defined in the outer scope because of the lexical (static) scoping. Even function executed outside of its lexical scope can access the variables defined in its lexical scope.

How can you identify a closure? If a function uses a variable that is not defined inside the function scope, it is probably a closure.

Top comments (0)

Forem Shop
Want to rep DEV and be comfy at the same time?
Check out the DEV shop!