Closures
suggest changeWhen a function is declared, variables in the context of its declaration are captured in its scope. For example, in the code below, the variable x is bound to a value in the outer scope, and then the reference to x is captured in the context of bar:
var x = 4; // declaration in outer scope
function bar() {
console.log(x); // outer scope is captured on declaration
}
bar(); // prints 4 to console
Sample output: 4
This concept of “capturing” scope is interesting because we can use and modify variables from an outer scope even after the outer scope exits. For example, consider the following:
function foo() {
var x = 4; // declaration in outer scope
function bar() {
console.log(x); // outer scope is captured on declaration
}
return bar;
// x goes out of scope after foo returns
}
var barWithX = foo();
barWithX(); // we can still access x
Sample output: 4
When foo is called, bar keeps a live reference to foo's variables. After foo returns, bar can still read and modify x. bar is the closure: a function plus the environment it captured. The binding is live, not a copy of the value x had at declaration time.
Private data
This lets us do some interesting things, such as defining “private” variables that are visible only to a specific function or set of functions. A contrived (but popular) example:
function makeCounter() {
var counter = 0;
return {
value: function () {
return counter;
},
increment: function () {
counter++;
}
};
}
var a = makeCounter();
var b = makeCounter();
a.increment();
console.log(a.value());
console.log(b.value());
Sample output:
1
0
Each call to makeCounter() creates a new environment with its own counter. The functions in the returned object close over that environment, so a and b do not share a counter.
Immediately-invoked function expressions (IIFE)
Closures are also used to prevent global namespace pollution, often through the use of immediately-invoked function expressions.
Immediately-invoked function expressions (or, perhaps more intuitively, self-executing anonymous functions) are essentially closures that are called right after declaration. The general idea with IIFE’s is to invoke the side-effect of creating a separate context that is accessible only to the code within the IIFE.
Suppose we want to be able to reference jQuery with $. Consider the naive method, without using an IIFE:
var $ = jQuery;
// we've just polluted the global namespace by assigning window.$ to jQuery
In the following example, an IIFE is used to ensure that the $ is bound to jQuery only in the context created by the closure:
(function ($) {
// $ is assigned to jQuery here
})(jQuery);
// but window.$ binding doesn't exist, so no pollution
See Closures on MDN for a longer explanation.