When you stop using var
in a declaration of a variable, you are declaring it in the global context, independent of the scope in which you declared it.
See:
function call_me_baby() {
a = 1;
var b = 2;
}
call_me_baby();
console.log(typeof(a), typeof(b));
Note that the a
variable has been "sent" to the global scope. The variable b
was limited to the scope of call_me_baby
.
When you make a declaration of a variable without using var
, we could say that it is the equivalent of doing the assignment directly on the object window
.
See:
call_me_baby() {
window.a = 1;
}
In the specific case of for
, the same thing would happen if you did not use var
to declare the variable. The variable i
would be implicitly defined in the global scope, regardless of the scope in which for
is invoked.
You can even use var
in 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 failure to declare i
could cause problems with collision of names and undue declarations.
Another important note is that with the use of "use strict"
, the lack of var
in the i
statement could generate an error.
(function () {
"use strict";
a = 1;
})();
See more at: