Closures

BrandonDusch580 total contributions
Published Mar 25, 2022
Contribute to Docs
Closures are functions that can refer to variables and other bindings beyond their scope, even after being called.
Example
Each time a new function is defined, a closure is created.
let myGlobalString = 'World';function outer() {let myLexicalString = 'Hello';function inner() {myLocalString = `${myGlobalString}, ${myLexicalString}!`;return myLocalString;}return inner;}
This example describes the three primary scopes visible to closures:
myGlobalString
exists in the global scope since it is not defined inside something else, like a function.- From the point-of-view of the
inner()
function, everything outside its scope (outer functions, the global environment, etc.) is in the lexical environment, includingmyLexicalString
andmyGlobalString
. - Inside the
inner()
function is a locally-bound variable,myLocalString
, that uses all the variables from its lexical environment.
Codebyte Example
Another common instance of JavaScript closures is with callbacks.
In the example below, the setInterval()
function creates a closure in the count()
callback that captures the references to the global variables myInterval
and counter
. Each second, counter
is incremented by one, with its value preserved from the previous call. After it gets to seven, myInterval
is cleared and reset to null
:
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.