“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

Leave a Comment