LearnFrenzy
Sign in Take a free test

Scope and Hoisting · Predict the Output · Question 6

Two counters from one factory Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
function counter() {
  let c = 0;
  return () => ++c;
}
const c1 = counter();
const c2 = counter();
c1();
c1();
console.log(c1(), c2());
  • A 3 1 Correct
  • B 3 4
  • C 1 1
  • D 2 1
Correct Answer: Option A

Each call to counter() creates a new scope with its own c. c1 has been called three times, c2 once.

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