Skip to content

JavaScript Private Class Fields

Introduction and code samples on using private class fields in JavaScript.

THE AHA STACK MASTERCLASS

Now open with 50% off launch discount!

Before the introduction of private class fields, we could not really enforce private properties on a class. We used conventions instead, maybe using _ as an hint that the field is private, like this:

class Counter {
  _count = 0

  increment() {
    this._count++
  }
}

But we could access the count using

const counter = new Counter()
counter._count

We can now 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. Trying to access it will raise a syntax error.

This is part of the new class fields proposal, which you can use since Chrome 72 and Node 12.


→ Get my JavaScript Beginner's Handbook

I wrote 20 books to help you become a better developer:

  • Astro Handbook
  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • CSS Handbook
  • Node.js Handbook
...download them all now!

Related posts that talk about js: