Web Development

Archive for March 2009

One fact that many JavaScript developers don’t realize is that there are only two levels of scope in JavaScript – the global scope and the function scope. Usually we find code like:

function doSomething(){
    a = 1;
}

Here we are not defining a variable called ‘a’ we are just assigning a value to a global variable with the same name. Such statements inside function scope should be avoided for simple reason that global variables result in complicated data flow. The right way to do is:

function doSomething(){
    var a = 1;
}

The point is that although JavaScript is not strict about variable declaration, ‘a=1’ is not a convenient alternative for ‘var a=1’.