JavaScript Closures
Published Mar 25, 2022
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:
myGlobalStringexists 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, includingmyLexicalStringandmyGlobalString. - 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:
Learn JavaScript on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours