OOP in JS: Private class properties

Hey, make sure you join my 🥾 ⛺ BOOTCAMP waiting list, next cohort in March/April/May 2025

When you define a property on a class, once you got 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 that enforce private fields:

class Counter {
  #count = 0

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

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

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