Jabbering Giraffe

JavaScript Scope

This is an issue that popped up with a colleague yesterday. Roughly, there was some code like this.

  function setUpStuff() {
    var items = cssQuery("#stuff p");
    for (var i = 0; i 

Unfortunately, even if cssQuery() returns a list of three items, every call to alert() will show the last item. Why?

It's all down to the fact that JavaScript doesn't have block-scoped variables. It only has function-scope.

In the context of the code above, it means that item exists from the point of entry to setUpStuff(). It's just undefined until the we get into the loop. The consequence of this is that each time we assign onclick, we're referring to the same variable.

The solution is to create another function scope, of course.

  function setUpStuff() {
    var items = cssQuery("#stuff p");
    for (var i = 0; i 

This now works as expected, because inside setUpAStuff(), we're referring to a different variable each time (you could also use an anonymous function). This is definitely one of the more confusing areas of JavaScript (though JSLint does pick up on this).

* Block-Structured JavaScript
* Core JavaScript 1.5 Guide:Block Statement (on devmo)