LearnFrenzy
Sign in Take a free test

Closures · Exercise 3 of 4

Closures Find the Error

  • 15 questions
  • Page 2 of 2
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

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 11 Easy

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]());
A Arrow functions cannot read arrays
B pages must be declared with let
C All handlers share one var i, which is 3 (past the end) when they run – use let i
D push copies the wrong function
Question page & discussion
Question 12 Medium

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
let count = 0;
function makeCounter() {
  return () => ++count;
}
const likes = makeCounter();
const views = makeCounter();
likes();
likes();
console.log("views:", views());
A Arrow functions always share variables
B makeCounter must be called with new
C ++count should be count++
D count is declared outside the factory, so every counter closes over the same variable – move let count = 0 inside makeCounter
Question page & discussion
Question 13 Hard

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());
A Spread cannot add items
B IIFEs cannot capture arrays
C report closed over a snapshot of the original (empty) array; add replaces items with new arrays – make report read the live variable: () => items.length
D items must be a const
Question page & discussion
Question 14 Medium

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    if (!cache.has(args[0])) cache.set(args[0], fn(...args));
    return cache.get(args[0]);
  };
}
const power = memoize((base, exp) => base ** exp);
console.log(power(2, 3), power(2, 10));
A Map cannot store numbers
B ** is evaluated before the cache
C The cache key uses only the first argument, so (2, 10) hits the entry stored for (2, 3) – build the key from all arguments, e.g. JSON.stringify(args)
D Rest parameters drop the second argument
Question page & discussion
Question 15 Easy

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
function makeTimer() {
  let seconds = 0;
  return {
    tick: () => ++seconds,
    reset: () => { let seconds = 0; },
    get: () => seconds,
  };
}
const t = makeTimer();
t.tick();
t.tick();
t.reset();
console.log(t.get());
A let seconds inside reset creates a new local variable that shadows the private one – write seconds = 0
B Arrow functions cannot change outer variables
C get should call tick
D reset must return seconds
Question page & discussion
Up next · Exercise 4Closures Coding Problems10 questions

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links