The first version:
for (var x in set) {
...
}
declares a local variable called x
. The second version:
for (x in set) {
...
}
does not.
If x
is already a local variable (i.e. you have a var x;
or var x = ...;
somewhere earlier in your current scope (i.e. the current function)) then they will be equivalent. If x
is not already a local variable, then using the second will implicitly declare a global variable x
. Consider this code:
var obj1 = {hey: 10, there: 15};
var obj2 = {heli: 99, copter: 10};
function loop1() {
for (x in obj1) alert(x);
}
function loop2() {
for (x in obj2) {
loop1();
alert(x);
}
}
loop2();
you might expect this to alert hey
, there
, heli
, hey
, there
, copter
, but since the x
is one and the same it will alert hey
, there
, there
, hey
, there
, there
. You don't want that! Use var x
in your for
loops.
To top it all off: if the for
loop is in the global scope (i.e. not in a function), then the local scope (the scope x
is declared in if you use var x
) is the same as the global scope (the scope x
is implicitly declared in if you use x
without a var), so the two versions will be identical.