What's the correct way to write a for-in
loop in JavaScript? The browser doesn't issue a complaint about either of the two approaches I show here. First, there is this approach where the iteration variable x
is explicitly declared:
for (var x in set) {
...
}
And alternatively this approach which reads more naturally but doesn't seem correct to me:
for (x in set) {
...
}
Use var
, it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var
statement. If it cannot find a var
then it is global (if you are in a strict mode, using strict
, global variables throw an error). This can lead to problems like the following.
function f (){
for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2
If you write var i
in the for loop the alert shows 2
.