AI Workshop: learn to build apps with AI →
OOP in JS: Private class properties

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


When you define a property on a class, once you have an object you can access that property freely, getting and setting its value.

Sometimes however it’s important to keep things private.

We can use private class fields to keep data private:

class Counter {
  #count = 0

  increment() {
    this.#count++
  }
}

We can’t access this value from outside the class.

You need to add a method to get its value:

class Counter {
  #count = 0

  increment() {
    this.#count++
  }
  getCount() {
    return this.#count
  }
}

const counter = new Counter()

counter.increment()
counter.increment()

console.log(counter.getCount())

Lessons in this unit:

0: Introduction
1: Classes
2: Class methods
3: ▶︎ Private class properties
4: Constructors
5: Inheritance
6: Prototypes