"var" or no "var" in JavaScript's "for-in" loop?
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
.
JavaScript Scoping and Hoisting
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.
You really should declare local variables with var
, always.
You also should not use "for ... in" loops unless you're absolutely sure that that's what you want to do. For iterating through real arrays (which is pretty common), you should always use a loop with a numeric index:
for (var i = 0; i < array.length; ++i) {
var element = array[i];
// ...
}
Iterating through a plain array with "for ... in" can have unexpected consequences, because your loop may pick up attributes of the array besides the numerically indexed ones.
edit — here in 2015 it's also fine to use .forEach()
to iterate through an array:
array.forEach(function(arrayElement, index, array) {
// first parameter is an element of the array
// second parameter is the index of the element in the array
// third parameter is the array itself
...
});
The .forEach()
method is present on the Array prototype from IE9 forward.