Reusing JavaScript "i" for loops

I recently started using PHP Storm (love it) and noticed that it declares "var i" in declarations for loops as duplicates in JavaScript. I found out that apparently the scope of this variable exists outside of the loop.

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

      

When I do the next for loop, should I declare var i again? Or should I just say i = 0? I know I can do it, but one seems bad and the other bad.

For one thing, you don't have to re-declare a variable that is in scope, but if I, for example, remove the first for loop that declares "i" then everything else breaks down.

+3


source to share


2 answers


JavaScript has only level scoping, no block level level. So, if a variable is declared anywhere inside a function, it will be available to the entire function. So, you don't need 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();

      



Will be printed,

undefined
10

      

i

declared in a function, but for

i

no value is assigned until the loop is executed . Thus, it will have a default value undefined

.

+3


source


you don't need to declare it again. you can just reassign the i value for the next loop like



              for (i = 0; i < 5; i++)
                {
             // Do anything
                  }

      

+3


source







All Articles