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 avarstatement. If it cannot find avarthen 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.If you write
var iin the for loop the alert shows2.JavaScript Scoping and Hoisting