JavaScript Scoping Using Closures

In JavaScript all functions and variables are often ‘hoisted’ to global scope, effectively making them global variables. This is potentially bad, as the following demonstrates:

if (true) {
    var x = 0;
}

alert(x); //alerts "0"

Here, even though ‘x’ is defined in a block, it is given global scope, and hence accessible outside the block. (For a demo, see http://jsfiddle.net/vRmLL/)

If we define our variable within a function, however, the scope is retained within the function. So the following will not work:

function SomeTest() {
    var y = 0;
}

alert(y); //undefined – a scoped variable - just what we want!

So, by using functions we can introduce scoping into JavaScript:

(function() {
    var z = 0;
})();

alert(z); //undefined – just what we want!

The last () executes everything in the body of the anonymous function. This pattern is called a closure.

This is a very simplistic overview of them. A more comprehensive one can be found in Morris Johns’ article JavaScript Closures for Dummies.

Leave a Reply