简体   繁体   中英

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?

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.

There's a difference. If you haven't declared key , var key will declare key . If you have, it's a redeclaration and not really a great thing to do, but it doesn't matter that much.

If you haven't declared it, not declaring it and using it, like in your second sample, is bad. It will leak globally, break in strict mode , and be slow.

If you're looking for a recommendation, always go for the var version, it's both safer (as its scope is the smallest possible) and faster (as the interpreter won't have to search if the variable already exists in the whole global scope). Plus it's recommanded by Google .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM