I have seen both….variable declaration in or before the for statement. Which is better? Here is an example snippet.
MC.initAll = function() {
var iterate = [MC, Su],
l = iterate.length,
i,
key;
for( i = 0; i < l; i++ ) {
for( key in iterate[i]) {
if( iterate[i].hasOwnProperty(key) && iterate[i][key].hasOwnProperty("init") ) {
iterate[i][key].init();
}
}
}
}
Pros of putting at top of function outside the for statement:
- less code due to using the same var statement
- already hoisted , js does not have to
- internal working made more explicit
- will pass jshint.com
Pros of putting in the for statement
- easy visual inspect to verify declaration took place in function
It is personal style. Which is “better” is purely a matter of opinion. The javascript interpreter will hoist all variable definitions to the start of the variable block no matter where the
varstatement appears.I personally like to put my var in the
forloop just so there is no accidental forgetting and using an implicit global variable, but that’s just a personal style choice. I know others like all variables declared explicitly at the start of the function.