JavaScript

For loop does not create a new scope

Unlike in other languages, the content of a for loop is not in a new scope. Let me show you.

var elements = document.getElementsByTagName("*");
for (var i = 0; i < 10; i++){
    // inside the loop
    var current = elements[i];
    // do some work
}
// outside the loop
console.log(current,i); // prints the last elements and the 10th index

Weird huh? So it means, these variables are still available outside the loop. The same goes for your while loop, switch statement, and so on.

To avoid this confusion, it makes more sense to create these variables outside of the loop to make a clear distinction of variables that are accessible throughout the scope. Define them in the top part of your function:

var elements = document.getElementsByTagName("*"),
index, // not giving a value assigns null to the variable
length = elements.length,
current; // not giving a value assigns null to the variable

for (index = 0;index <length; index++) {
    current = elements[index];
    // do some work
}

Now no one will be confused that current and index have values outside of the loop.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only