Accidental Global Variables

Recently I've been helping folks out with Javascript problems online or in person a fair bit. Some common problems or mistakes crop up repeatedly and I've kept a list of them. I am going to write about these common problems in a series of articles, starting with this one. The first problem is accidentally leaking global variables, let's get started!

As I already mentioned in a recent post, global variables are easily leaked in Javascript. A variable i declared within a function like this

function f(){
    i = 1
}
f()
console.log("I can still see i: " + i)

The solution is to declare i as a local variable using the var statement.

function f(){
    var i = 1
}
f()
console.log("Now I can't see i: " + i)

The same thing happens in the for clause of for-loops.

for (i = 0; i < array.length; i++){
    ...
}

Don't think just because it's a for-loop, it is some how different. I can understand feeling a little funny about declaring a var inside the for clause, but it totally works!

for (var i = 0; i < array.length; i++) {

Recommendation: Always declare your variables using the var statement, no matter what. Using a static analysis tool like JSHint will help you catch global variable leaks.

Don't miss the entire series: 7 Common Javascript Mistakes or Confusions

blog comments powered by Disqus