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.
Continue reading about The commonest javascript bug
Semantically similar articles hand-picked by GPT-4
- Closure and currying magic for cleaner javascript
- JS object optimization bug in Chrome 52
- A lesson about client-side templating
- A Fast Mutex Lamport Lock with JavaScript Promises
- I broke AJAX in Chrome 52 ?
Learned something new?
Read more Software Engineering Lessons from Production
I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.
Subscribe below 👇
Software Engineering Lessons from Production
Join Swizec's Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open 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. 👌"
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
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 ❤️