Skip to content
Swizec Teller - a geek with a hatswizec.com

The commonest javascript bug

CAEN 25th Anniversary Celebration

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](http://en.wikipedia.org/wiki/Event%28computing%29 "Event (computing)") 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

Did you enjoy this article?

Published on February 24th, 2012 in closures, For loop, JavaScript, JSON, Languages, Programming, Scope (computer science), Uncategorized

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️