Find the bug · #31 · Loops and closures Easy JavaScript
Every reminder says “undefined”
A to-do app schedules a reminder per task, and every reminder says “undefined”.
On this page
The report
A to-do app schedules a reminder for each task. When the reminders go off, every single one says “undefined” instead of the task’s name.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Fires each task's reminder after a short delay.
function scheduleReminders(tasks, notify) {
for (var i = 0; i < tasks.length; i++) {
setTimeout(() => notify(tasks[i]), 10);
}
}Read it, then pick a line.
When the timers fire, what is i? Is there one i, or one per turn of the loop?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const seen = [];
scheduleReminders(['Pay rent', 'Call mom', 'Gym'], (t) => seen.push(t));
await new Promise((r) => setTimeout(r, 50));
console.log(seen.map(String).join(' | '));It prints
undefined | undefined | undefined
It should print
Pay rent | Call mom | Gym
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 declares the loop counter with var. A var belongs to the whole function, so all the callbacks share one i, and by the time the timers fire the loop has finished and i is 3. tasks[3] is undefined. With let, each turn of the loop gets its own i.
The fix
1// Fires each task's reminder after a short delay.2function scheduleReminders(tasks, notify) {3 for (var i = 0; i < tasks.length; i++) {3 for (let i = 0; i < tasks.length; i++) {4 setTimeout(() => notify(tasks[i]), 10);5 }6}How you’d find it
- Reproduce: three tasks, wait for the timers, and every reminder gets
undefined. - Undefined from
tasks[i]meansiis out of range when the callback runs. Log it inside the callback: it’s 3 every time. - The callbacks run after the loop ends, and a
varis one variable for the whole function. They all read its final value.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
const seen = [];
scheduleReminders(['a', 'b'], (t) => seen.push(t));
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(seen, ['a', 'b']);Where else this bites
- Click handlers attached in a loop with
var. - Python’s closures do the same thing (see “Every tab button opens the last tab”).