Question

I make use of a for in loop in a piece of JavaScript logic. Should I use the var keyword or not?

When I run a for-in loop as per W3School's example, without the var then, as a side effect, it gets defined as a property on the global scope (window):

(function () {

  var object = {
      a: 1,
      b: 2
  }
  for (varName in object) {
      alert(varName + " is" + object[varName])
  }

})();

alert(window.varName) //Returns "b" !
//This returns undefined when the for-in is rewritten as for (var varName in object).

edit: here is a fiddle of the above code for your enjoyment: http://jsfiddle.net/94uEh/

Which is the correct, preferred form? - Note that I wish to support IE 8 (EcmaScript < 5)

Was it helpful?

Solution

You should always use var, if you want the value to be local.

Using the keyword object for a variable, is not recommended, you might run into undefined behavior across browsers.

Also you should generally avoid applying anything that is suppose to be local to the global scope.

This is bad:

for (varName in object) {
    alert(varName + " is" + object[varName])
}

This is correct:

for (var varName in object) {
    alert(varName + " is" + object[varName])
}

If you need to access this value in the global scope, you are probably doing it wrong. Also having this in the global scope is useless, as it will only be the last value, that will exist in the varName.

OTHER TIPS

You should always use var, otherwise you are accessing a global variable (and there's a risk you are overwriting someone's else variable)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top