Saturday, December 19, 2009

JavaScript's Function Scope

Those developers who are coming from a C background may find JavaScript's scoping rules a bit confusing.

Let's take a look at the following C code:

#include <stdio.h>

int main () {
    int n = 5;
    if (1) {
        int n = 2;
    }
    printf("n is %d", n);
}

The output of the above code is:

n is 5


Now let us implement the above code in JavaScript:

var scoping = function () {
    var n = 5;
    if (1) {  
        var n = 2;
    }
    alert('n is ' + n);
};

What do you think the above code alerts?

If you answered n is 5, then you are wrong


This is because, unlike C, JavaScript only supports Function Scope and not Block Scope.

What this means is that JavaScript creates a new scope only with a function:

var scoping = function () {
    var n = 5;
    var x = function () {  
        var n = 2;
    };
    alert('n is ' + n);
};

Now, n is 5 is alerted because a new scope has been created with the inner function and thus it's encapsulating the inner variable n.