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.

for the last one, shouldn’t be :
// Result: ‘something’ ?
da-mi reply daca gresesc, nu sunt chiar expert :)
You’re right. Corrected.
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.
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.
That’s good. However the strict mode was introduced recently in the language, right?
I am no sure when it was introduced, however it has been around at least since version 1.5 (november 2000).
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.