Closures

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, including myLexicalString and myGlobalString.
  • 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:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy