javascript - Re-declaring variable in multiple for loops - for(var i ...) -


in past used write loops this:

// count 10 for(var = 1; <= 10; i++) {     console.log(i); }  var message = "we're done here!";  // count down 10's 100 for(var = 100; >= 0; -= 10) {     console.log(i);      if(i === 0) {         alert(message);     } } 

then, after failing every syntax code checker under sun , being told not re-declare variables, ended coding this, using single var statement @ top of each scope:

var i,  message = "we're done here!";  // count 10 for(i = 1; <= 10; i++) {     console.log(i); }  // count down 10's 100 for(i = 100; >= 0; -= 10) {     console.log(i);      if(i === 0) {         alert(message);     } } 

personally, keeping var seems make code more maintainable, when don't have worry whether i declared or not. i've seen similar issues brought on multiple var statements. if interpreter ignoring additional declaration, , treating assignment, don't see why bad thing.

so, if ignore conventions, , style guides, can re-declaring i in each loop potentially cause problems, performance or otherwise?

(aside failing said syntax checkers , douglas crockford getting mad @ you).

so, if ignore conventions, , style guides, can re-declaring in each loop potentially cause problems, performance or otherwise?

no, not cause problems @ run-time or affect performance.

all var declarations within scope hoisted top of block (before code runs in block) dups combined. parser ignores duplicate declarations.

the downsides can think of adds slight bit more size code (extra var) vs. combining var declarations @ top. but, if run minimizer, size should removed.

the warning , general style recommendation because duplicate var declaration can lead reader or coder accidentally think declaring new, unused local variable when, in fact, variable in use , may have value , other code may using variable. if know not case, not harm other perhaps make easier accidentally make mistake.


fyi, for loop, es6 solves issue let declaration which, when used in for loop initializer declare variable uniquely scoped for loop.

// count 10 (let = 1; <= 10; i++) {     // scoped within loop     console.log(i); }  // count down 10's 100 (let = 100; >= 0; -= 10) {     // scoped within loop     console.log(i);      if(i === 0) {         alert(message);     } } 

for personal style, find code more maintainable if keep var declaration for loop, if reusing same variable (easier move code around , see declaration is). find each loop lot more self contained. and, declare differently (outside loop) if ever trying use loop variable outside of for loop. if i'm in es6 environment, use let for loop variables.

i avoid redeclaring other variable within function because seems more mistake purposeful intention , there seems maintenance benefit redeclaring it.


Comments