Last Friday while doing some testing I came across an interesting javascript problem. I noticed that my for loop variables in the script were going nuts.. After a little bit of tinkering around (by tinkering I mean putting a ton of javascript alerts) I managed to identify the problem.

Background

Javascript has two scopes for variables, local and global. Variables assigned outside function are global and variables assigned inside the function call WITH the keyword “var” are local. However, if you forget to declare the local variable with the keyword var, it assigns itself as a global variable. 

Example

Heres a simple example to demonstrate the problem. 

function function1() {  
 for (x = 0; x < 5; x++) {
  document.write(x + ' , ');
   function2();
 }
}
function function2()
 for (x = 0; x < 5; x++) {
  document.write(x + ' , ');
  }
}

Problem

As you might think that the output of the script above would be like 
0 , 0 , 1 , 2 , 3 , 4 , 1 , 0 , 1 , 2 , 3 , 4 , 2 , 0 , 1 , 2 , 3 , 4 , 3 , 0 , 1 , 2 , 3 , 4 , 4 , 0 , 1 , 2 , 3 , 4 (desired output)

But its NOT. It is actually 

0 , 0 , 1 , 2 , 3 , 4

because the X variable in both function calls are assigned as a global (with the lack of var keyword) and the value is getting overridden by the x variable in function2. 

Solution

To solve the problem, declare the  X variable in function calls with the keyword var.

for (var x = 0; x < 5; x++)

So if you like to avoid certain bugs in your code and a few hair tearing panicky moments, please declare your local variables with var.