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 (7)

  • for the last one, shouldn’t be :
    // Result: ‘something’ ?

    da-mi reply daca gresesc, nu sunt chiar expert :)

  • Scott says:

    Thank You.
    A simple answer was what i wanted not a hour read one.
    Why couldn’t they all just say:
    “var is the opposite of the global keyword from PHP”.
    Thank you.

  • Yvar says:

    It is true that you can use the var keyword like that. But declaring a variable without the var keyword always raises a strict error in javascript.
    The specification clearly states:
    “By simply assigning it a value. For example, x = 42. This always declares a global variable and generates a strict JavaScript warning. You shouldn’t use this variant.”

    In other words, the var keyword is mandatory.

  • Yvar says:

    I am no sure when it was introduced, however it has been around at least since version 1.5 (november 2000).

  • Yvar says:

    Just to make sure I checked the ECMAScript 3rd edition (1999), and that implies that leaving out var is not allowed at all. So the fact that you can define/declare a variable without var seems to have been a proprietary issue anyway.