Why You Should Always Use var In JavaScript for Loops

I ran into a well-known JavaScript issue with variable scope recently that resulted in a difficult to find bug. The moral is that when writing a JavaScript for loop you should always use the ‘var’ keyword for the loop index variable. Consider this code:


var fruits = [ ‘apple’, ‘banana’, ‘cherry’ ];
var colors = [ ‘red’, ‘green’ ];

function ShowFruitsAndColors()
  for (var i = 0; i < fruits.length; ++i) {

function ShowColors()
  for (var i = 0; i < colors.length; ++i) {

<body onload=”ShowFruitsAndColors();”>

When the page is loaded the ShowFruitsAndColors function will be called. That function alerts apple-red-green-banana-red-green-cherry-red-green as you’d expect. Using the ‘var’ keyword makes the two index variables i local in scope and therefore different from each other. But if you leave out the ‘var’ keyword in the for loops, the output would be just apple-red-green. Without the ‘var’ keyword variable i implicitly assumes global scope so there is just one i variable and the two loops get confused.

This entry was posted in Software Test Automation. Bookmark the permalink.