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.
Should you create a var inside a for-in loop?
-
01-06-2022 - |
Question
for(var key in object){
//process object[key]
}
or just
for(key in object) {
//process object[key]
}
Is there a difference?
Solution
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow