Javascript scope in for loops

In JavaScript, you don’t need to define your variables.  You can just up and use any variable as you see fit, like this:

asdfasdf = 'asdfasdf';

However, these variables will then be created in a global scope, which is bad.

I came across a bug today that involved for loops and globally undefined variables.  It’s not as clear what is happening when the counter variable is first used inside the for declaration, but the result is the same: a global variable:

function test2() {
     for (i = 0; i < 10; i++) {
         alert('now i is ' + i);

 function test3() {
     for (i = 0; i < 10; i++) {
         // do whatever here

In this example, test2()’s for loop will only run 1 time, because test3’s loop ends up using the same variable.

To fix this problem you need to define your looping variables:

for (var i=0; i < 10; i++)

This is a best practice that you should remember to do.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s