The commonest javascript bug

CAEN 25th Anniversary Celebration

CAEN 25th Anniversary Celebration (Photo credit: rosefirerising)

Every couple of weeks somebody will come running to me: “Swizec, Swizec, I did everything right, but this javascript isn’t doing what it’s supposed to! Whatever I click only the last item works. Halp!”

Every time it’s the same bug – people just don’t understand how loops and closures play together in javascript. Invariably they loop through an array, attach the index to an event, then get frustrated when, upon triggering the event, that particular variable seems to have the wrong value.

The code usually looks something like this:

json = JSON.parse(this.responseText);
for (i = 0; i < json.links.length; i++) {
       params = json.links[i];
 
       row = $$.ui.createRow({
                 // use params for settings, it works
                 click: function () {
                    var modalBrowser = new MiniBrowser({
                                        // it all breaks down here
                                        url: params.url,
                    });
       });
       // do some other stuff
}

Can you spot the problem?

On the first use of params everything is happy, using the local variable, which is updated on every loop iteration. But when that click event is triggered it still uses the local params variable … that was updated on every loop iteration.

By now, the loop has long since completed and that variable holds the last value – causing a weird-looking bug that is difficult for newbies to fix because, hey, why should I know about how pointers work? This is a scripting language damn it!

Luckily the fix is very simple:

json = JSON.parse(this.responseText);
json.links.map(function (params) {
 
       row = $$.ui.createRow({
               // use params for settings, it works
               click: function () {
                    var modalBrowser = new MiniBrowser({
                                   // it magically still works here
                                   url: params.url,
                    });
       });
       // do some other stuff
});

Just change the for loop to a map and you don’t even have to fix anything else. Everything works as usual, except now all the code is wrapped up in a closure and caries a reference to the whole variable scope around. Simply put – when the click event is triggered all the variables that were known when it was set are still there, with exactly the same values.

Generally speaking, even a modest understanding of closures (like I have) will make it much easier to write javascript. Might even help you fix a memory leak or fifty.

Enhanced by Zemanta

Related Posts

---
Need a freelance developer? Email me!

You should follow me on twitter
 Subscribe to RSS

One response so far

  • Anonymous

    Moral of the story? Map is awesome. See also the fold family.

    I’ve come to the conclusion that all the scope pain people run into with Javascript is because it confuses functional, OO, and procedural scoping rules. If you write in procedural or OO style you really should avoid closures unless you really know what you’re doing, and likewise if you write in functional style you should avoid for loops unless you really know what you’re doing.

    On a related note, underscore is an awesome JS library and brings a bunch of the awesome higher order functions from other functional languages into JS.

« I made a steampunk costume Unit testing is for lazy people »