LearnFrenzy
Sign in Take a free test

Closures · Find the Error · Question 12

Bug: separate counters share a count Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

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 Correct
Correct Answer: Option D

Each call creates a new environment only for variables declared inside the function. With count inside, views() returns 1.

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