Ben McCormack Ben McCormack - 3 years ago 185
Javascript Question

Javascript for loop index variables become part of global scope?

Perhaps I'm not aware of how

loop index variables get scoped, but I was very surprised when one of my loops didn't complete, seemingly because a function called from within a loop contained an
for its
loop index as well.

Here's a little script I put together to demonstrate this behavior:

var loopOne = function(test) {
for(i = 0; i < test.length; i++)

var getMask = function(pass) {
var s = "";
for (i = 0; i < pass.length; i++) {
s = s + "*";
return s;


If I run this in Chrome and look at the console log, I should see
five times. However, I only see it once. Upon further inspection, if I type
in the Chrome javascript console, it will output 6 (
= 'hello'.length + 1
). This makes me think that
has become a part of the global scope and is not limited to the scope of the
loop for which it was needed.

Is this correct? If so, what's a better practice for defining the index variable of a
loop in javascript?

Answer Source

In Javascript, variables are scoped with the var keyword. When declaring variables with var, the variable is scoped to the current function. When assigning to a variable without using the var keyword, it is assumed you're talking about an already defined variable in the same or a higher scope. If none is found, the variable is created in the highest scope.

Bottom line: declare all your variables using var.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download