When you stop using the var
in a variable declaration, you are declaring it in the global context, independent of the scope in which you declared it.
Behold:
function call_me_baby() {
a = 1;
var b = 2;
}
call_me_baby();
console.log(typeof(a), typeof(b));
Note that the variable a
was "sent" to the global scope. Already the variable b
was limited to the scope of call_me_baby
.
When you make a declaration of a variable without using the var
, we could say it’s the equivalent of making the assignment directly on the object window
.
Behold:
call_me_baby() {
window.a = 1;
}
In the specific case of for
, would happen the same thing if you didn’t use var
to declare the variable. The variable i
would be implicitly defined in the overall scope, regardless of the scope in which the for
is invoked.
You can even use the var
in the for
in two ways:
var i;
for (i = 0; i < 10; i++) {}
Or
for (var i = 0; i < 10; i++) {}
It is important to note that the non-disclosure of i
could cause collision problems of names and improper statements.
Another important note is that with the use of "use strict"
, the lack of var
in the statement of i
could generate an error.
(function () {
"use strict";
a = 1;
})();
See more in:
Related: When to use var in javascript?
– Wallace Maxters
You need something better?
– Maniero