Javascript: Why you should use the ‘var’ keyword

I always wondered what was the purpose of the var keyword, since in JavaScript, you can just use a variable without declaring it.

Today I found out.

Say you have this code:

foo = 1;
function test() {
	foo = bar;
}
test();
alert(foo);

// Result: 'bar'

It turns out that foo will be modified from the test() function.

If you are coming from PHP scripting, like I am, you will find this very unusual.

Now, if you used var:

foo = 1;
function test() {
	var foo = 'bar';
}
test();
alert(foo);

// Result: 1

foo would remain unchanged.

It even works with functions declared as variables:

foo = 'something';
function test() {
	var foo = function() {
		alert('bar');
	};
}
test();
alert(foo);

// Result: 'something'

So, var affects the variable scope:

Inside a function, all undeclared variables are global. Only those declared with var are local. This becomes very important when you have a lot of scripts running on the same page.

You could say that var is the opposite of the global keyword from PHP.

comments powered by Disqus