What is the output of the following? “`js class Counter { #count = 0; increment() { this.#count++; } get value() { return this.#count; } } const c = new Counter(); c.increment(); c.increment(); console.log(c.value); console.log(c.#count); “`

JavaScript Professional Medium

JavaScript Professional — Medium

What is the output of the following? “`js class Counter { #count = 0; increment() { this.#count++; } get value() { return this.#count; } } const c = new Counter(); c.increment(); c.increment(); console.log(c.value); console.log(c.#count); “`

Key points

  • Accessing private fields in JavaScript using `#` is not allowed outside the class.
  • The correct way to access the count value is through the getter method `value`.
  • SyntaxError occurs when trying to access private fields directly.

Ready to go further?

Related questions