AniUI Academy

Fix the classic loop closure bug

easyFunctions & Closures+150 XPPractice

This is the bug that made let worth shipping. A loop builds one callback per item; because var i is function-scoped, all the callbacks close over the *same* i, and by the time any of them runs the loop has finished and i sits one past the end. Every handler reports the last index — or, as here, undefined.

The starter code contains exactly that bug. Fix makeLoggers(items) so it returns an array with one function per item, in order, where the function at index i returns the string i + ":" + items[i] — for example "0:a". The functions must be correct however many times and in whatever order they are called, and an empty input array must produce an empty array.

Arguments

itemsany[]
The array to build one logger per element from.

Returns

Array<() => string> — One logger per input item, in order. The logger at index i returns the string "i:items[i]".

Examples

const loggers = makeLoggers(["a", "b", "c"]);

loggers[0](); // "0:a"
loggers[1](); // "1:b"
loggers[2](); // "2:c"
// The buggy starter does this instead:
const buggy = makeLoggers(["a", "b", "c"]);
buggy[0](); // "3:undefined" — every closure shares the same `var i`

That is why the fix is a single-character change: var to let.

What it has to do

  • Return one function per item, in the same order as the input.
  • The function at index i returns i + ":" + items[i], so each closure captures its own index.
  • Calling the functions repeatedly or out of order returns the same results.
  • An empty input array returns an empty array.

Notes

  • let and const in a for header produce a *fresh binding per iteration*, so each closure captures a different i. This is the canonical difference versus var.
  • Pre-ES6 code solved this with an IIFE per iteration: (function (i) { … })(i). Same idea — create a new scope so each closure sees its own copy.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.