I am Hack Sparrow
Captain of the Internets.

Should you use “var” for initializing counter variables in For / For Each loops?


To var, or not to var, that is the question.

- Bill Shakespeare

What difference does the use of var in the for and for each loop constructs make?

With var

var o = [3,949,88,345]
for (var i in o) {
    console.log(i);
}

Without var

var o = [3,949,88,345]
for (i in o) {
    console.log(i);
}

They might mostly look and work the same but they make a difference. The difference could be insignificant or critical depending on your requirement. The counter variable will be initialized in the scope that contains the loop, and not within the scope of the loop. Infact, loops do not create scopes in JavaScript.

What does that mean? Observe the code below.

function foo() {
    var o = [3,949,88,345]
    for (i in o) {
        console.log(i);
    }
}

foo();
console.log(i);

Not using var created the counter variable in the global scope. The loop created a global variable, from within the function, potentially overwriting a previous value.

Now check the code below.

function foo() {
    var o = [3,949,88,345]
    for (var i in o) {
        console.log(i);
    }
}

foo();
console.log(i);    // i is undefined

The use of var created the counter variable in the function scope of foo. Meaning, the counter variable is confined to within the function - it won't overwrite any variable in the global scope.

I think it's obvious by now whether to use var or not in your loop constructs. Always use vars for initializing variables anywhere in your JavaScript code.

Notes

  1. Always use var to initialize variables.
  2. Variables created without var is created in the global scope.
  3. Loops do not create scopes in JavaScript.

Exercise
  • In which condition would using or not using var make no difference?
  • What are scopes in JavaScript?
  • What are closures in JavaScript?

Make a Comment