Search code examples
javascriptloopsscoping

Should you create a var inside a for-in loop?


for(var key in object){
  //process object[key]
}

or just

for(key in object) {
  //process object[key]
}

Is there a difference?


Solution

  • Yes, there's a difference. Whether you use var or not key will still be a variable, and its 'life' will not actually end after for is done, its scope will span till the end of the function. But if you do not use var - the key will be global.