6. Closures 1
This video will be using the first code example from the lesson text below.
What is a Closure?
To once again borrow from Kyle Simpson, "Closure is when a function is able to remember and access its scope even when that function is executing outside its scope."
One of the definitions we use often is this: A closure happens when a function is executed outside of the scope in which it was defined and relies on one or more variables in that original scope.
When a function is finished executing, JavaScript's "garbage collection" cleans up the function and removes any variables inside of its scope. This is to save memory. However, if those variables are being accessed (utilized) outside the function's scope somewhere else, they will stay around. This is closure. Let's look at an example:
var foo = function() {
var x = 1;
var bar = function() {
console.log(x);
};
return bar;
};
var baz = foo();
baz();
What do you expect to be the result of the code above? Copy and paste it and take some time to think through what's going on. Then read the following steps.
-
After compilation is done, the engine is ready to execute. During compilation in the global scope,
foo
andbaz
are set aside, then assigned to their values. -
When
baz
is assigned,foo
is invoked. -
We then step into the scope of
foo
and compilex
andbar
by assigning them to their values. -
Back in the global scope,
baz
is set to the result of invokingfoo
, which meansbaz
points to the functionbar
that lives inside the scope offoo
. -
Finally,
baz
is invoked, which is technicallybar
inside offoo
. That function relies onx
, thereforex
is still alive enabling us to log it in the global scope.
Why are Closures Useful?
First, can you think through some possible reason as to why you think closures could be useful?
This will make more sense in a few moments when we get to some more real world examples, but Closures in JavaScript enable us to have private variables. In the last example, foo
created a protective block around x
which we were not able to manipulate from the global scope. However, since we returned it, we were able to console log it (so we still have some use of it, but only inasmuch as our program allowed us to).
Let's look at some more examples.