0

My problem is understanding the purpose of the var in a for in loop as they both seem to work fine. For instance,

for(i in array) {
  console.log(i);
}

or

for (var i in array) {
 console.log(i)
}

Both produces the same result

So I am trying to understand the difference.

Thanks for the clarification.

code_legend
  • 3,547
  • 15
  • 51
  • 95
  • Depends where the loop is. You're explicitly declaring `i` in the second example rather making it a global variable which you do by not declaring it properly - it depends on its scope. But I would urge you [not to use `for in` loops for arrays](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea). – Andy Sep 06 '15 at 00:26
  • Maybe [why to use “var” inside for in loop?](http://stackoverflow.com/q/11931035/1529630) was a better dupetarget – Oriol Sep 06 '15 at 00:35
  • If you did'nt use "var" in for loop then it will be global variable which means where ever you call i in your code it has value and it would'nt function error – Ahmadbaba46 Sep 06 '15 at 00:42

0 Answers0