Debug fifteen JavaScript closure programs: SyntaxErrors in factories and IIFEs, runtime errors from const captures, wrong return values, the TDZ, missing arguments and private variables used from outside, and silent bugs from var loops, state outside the factory, stale snapshots, bad cache keys and shadowed variables.
Question 11Easy
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
main.js
const pages = ["Home", "Courses", "Contact"];
const handlers = [];
for (var i = 0; i < pages.length; i++) {
handlers.push(() => `Opening ${pages[i]}`);
}
console.log(handlers[0](), "|", handlers[2]());
AArrow functions cannot read arrays
Bpages must be declared with let
CAll handlers share one var i, which is 3 (past the end) when they run – use let i
Dpush copies the wrong function
Correct Answer: Option C
With let, each handler closes over its own i: "Opening Home | Opening Contact".
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
main.js
function createCart() {
let items = [];
const add = (item) => { items = [...items, item]; }; // replaces the array each time
const report = ((list) => () => list.length)(items); // captured the first array
return { add, report };
}
const cart = createCart();
cart.add("pen");
cart.add("ink");
console.log(cart.report());
ASpread cannot add items
BIIFEs cannot capture arrays
Creport closed over a snapshot of the original (empty) array; add replaces items with new arrays – make report read the live variable: () => items.length
Ditems must be a const
Correct Answer: Option C
The IIFE copied the reference to the first array into list. Because add assigns a new array each time, list never changes. Reading items directly sees the latest array.
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·