Fix the classic loop closure bug
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
ireturnsi + ":" + 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
letandconstin aforheader produce a *fresh binding per iteration*, so each closure captures a differenti. This is the canonical difference versusvar.- 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.
- 1.each function reports its own index
- 2.returns one function per item
- 3.stays correct when called out of order and twice
- 4.handles an empty array
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.