LearnFrenzy
Sign in Take a free test

Closures · Find the Error · Question 15

Bug: reset does not reset Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

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 Correct
  • B Arrow functions cannot change outer variables
  • C get should call tick
  • D reset must return seconds
Correct Answer: Option A

Declaring a variable with the same name hides the closed-over one. Assigning without let updates the private seconds, so get() returns 0.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links