Question 12
Back to Exercise
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
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!