Archive

Posts Tagged ‘scope’

JavaScript Scope

March 23, 2012 Leave a comment

In this blog post we will dig deeper into various aspects of JavaScript scope.  This is a pretty interesting topic  and also a topic which confuses many beginning JavaScript programmers.

Understanding JavaScript scope helps you write bug free programs (hmm.. atleast helps your troubleshoot things easily)

Scope control the visibility and lifetimes of variables and parameters.  This is important from the perspective of avoiding naming collisions and provides memory management service.

Unlike other languages, JavaScript does not have block level scope.  For e.g. take for instance the following piece of c# code.

public void Main () {
    int a = 5;
    if (true) {
        int b = 10;
    }
    // This will throw compile time error as b is not defined
    // and not within the scope of function Main();
    Console.WriteLine(b);
}

If you write the same code in JavaScript, then the value of ‘b’ will be available outside the ‘if’ block. The reason for this is JavaScript does not have block level scope. Scopes works at the function level and because of a feature called ‘hoisting’ all variable declaration in JavaScript is moved to the top of the function.

You can read more about hoisting here http://rajeshpillai.tekacademy.com/hoisting/

function scopeDemo() {
    var a = 5;
    if (true) {
        var b = 10;
    }
    // This will work even though 'b' is defined inside if block because of 'hoisting'
    alert(b);
}

scopeDemo();  // Invoke the function

Remember, Scope in JavaScript is at function level and not block level.

So, contrary to popular guidelines of most programming lanaguage to declare variables as late as possible, in JavaScript it is recommended to declare all your variables as early as possible.
Happy Scoping !!!
Categories: JavaScript Tags: ,