SiteKickr Web Development

A note on JavaScript variable scope

Way back in the early days of JavaScript, we can all admit to not really understanding the language, but rather using it almost as an extension of HTML, to product basic presentational effects. For me at least, it wasn't until web 2.0 hit that I started to take JavaScript a little more seriously and actually began to grasp the language.

One of the larger points of confusion was variable scope. Coming from desktop development, I was used to variables being scoped within the blocks that they were created. A variable declared within a function or code block, was available only to that function or code block, then it disappeared.

JavaScript, being an OO language does in-fact have similar scoping available, but in a syntactically different way. For example, if we have the following script:

var count;
(function() {
  count = 1;
})();


console.log(count);

1

The variable count is declared global, then the global variable is altered within a function. But, if we do not declare the count variable globally, but then declare it within our function, we get the same result:

 

(function() {
  count = 1;
})();

console.log(count);

1

How can this be? Shouldn't count have been scoped to the function? Not exactly. It all falls on the use (or lack of) of the var keyword. By using var within a function, you are telling JavaScript that this variable belongs to the function, and should not be globally scoped.

 

(function() {
  var count = 1;
})();

console.log(count);

undefined

 

In practice, while your code may still function if you litter the global space with variables, you should use the var keyword to keep them limited to the scoped needed by the script. This will keep your global scope clean, and I would imagine that it would reduce client-side memory use during script execution (although I have no evidence to back that up).

Most developers likely use the var keyword in practice, possibly without even knowing it's true meaning. But, probably the most common misuse of omitting the var keyword comes with for loops:

(function(myArray) {
  var count = myArray.length;
  for(i = 0; i < count; i++) {
    // do something
  }
})(myArray);

 

Notice how the i = 0 is completely absent of the var keyword. You are essentially setting the global variable i to 0. As you can imagine, in some cases, this could cause unexpected results. The proper way to run a for loop is to use the var keyword to initialize your counter (unless you have reason otherwise, of course):

(function(myArray) {
  var count = myArray.length;
  for(var i = 0; i < count; i++) {
    // do something
  }
})(myArray);