Search code examples
javascriptvariablesscopedeclarationduplication

Reusing "i" for JavaScript for loops


I recently started using PHP Storm (love it) and noticed that it flags declarations of "var i" in for loops as duplicate in JavaScript. I learned that apparently the scope of that variable exists outside of the loop.

for (var i = 0; i < 10; i++) {
    // Do anything
}
console.log(i); // i == 10

When I do my next for loop, should I declare var i again? Or, should I just say i = 0? I know I can do either, but one seems like bad style, the other like bad implementation.

On one hand, you shouldn't re-declare a variable that's in scope, but if I, for instance, delete the first for loop that declares "i", then everything else will break.


Solution

  • JavaScript has only function level scope, no block level scope. So, if a variable is declared anywhere within a function, it will be available for the entire function. So, you don't have to declare it again.

    The best practice is to declare all the variables used in the function at the beginning of the function.

    For example,

    function myFunction() {
        console.log(i);
        for (var i = 0; i < 10; i++);
        console.log(i);
    }
    
    myFunction();
    

    Would print,

    undefined
    10
    

    i is declared in the function, but till the for loop is executed, i is not assigned any value. So, it will have the default value undefined in it.