What is the output of the following code? “`js function counter() { let count = 0; return () => ++count; } const inc = counter(); console.log(inc()); console.log(inc()); “`

JavaScript Associate Medium

JavaScript Associate — Medium

What is the output of the following code? “`js function counter() { let count = 0; return () => ++count; } const inc = counter(); console.log(inc()); console.log(inc()); “`

Key points

  • The function counter returns a closure that increments a count variable.
  • The variable count is initialized to 0.
  • Each call to inc increments the count by 1.
  • The first call to inc returns 1, and the second call returns 2.

Ready to go further?

Related questions