# Closures
A closure can be thought of as a small bubble that gets wrapped around a variable to protect its original value, in order that it can be used later.
To understand closures you need to understand variable scope in JavaScript and how the JS interpreter will climb up through the different scopes looking for a match for variables that you use. Scope reference from week 2
# Lexical Scoping
This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available.
function init() {
let name = "Mozilla"; // name is a local variable created by init
function displayName() {
// displayName() is the inner function, a closure
alert(name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
2
3
4
5
6
7
8
9
The variable name
is declared inside the function init so it is available anywhere inside that function, even inside functions that are nested inside.
# From Lexical Scope to Closure
Now lets make a slight change to the code from above.
The displayName
function is being returned from the makeFunc
function after name
is declared but before displayName
is run to access the value of name
.
This has created a closure
around name
.
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
2
3
4
5
6
7
8
9
10
At some point in the future the displayName
function will be called to run. In order to prevent it from failing, it needs to know the value of name
. The value of name
is put inside a closure and saved along with the definition of displayName
.
The instance of displayName
maintains a reference to its lexical environment, within which the variable name
exists.
# Videos
This first video explains the concepts of closures.
This second video demonstrates how closures work within the context of a loop.
This final video asks a sample interview question to see if you understand closures. It also provides the solution.