JavaScript closures
Lukas Polak
Posted on September 4, 2020
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.
Posted on September 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.