Web Development

JavaScript: ‘var’ keyword and scope

Posted on: March 22, 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’.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: