Course contentsShow
← JavaScript
Lesson 1832 of 2,72338. Object-Oriented PatternsFree lesson

Private Class Fields with #

Using ES2022 # syntax for truly private fields and methods in class definitions.

Private Class Fields with

What you'll learn: How to use the # syntax introduced in ES2022 to create truly private fields and methods that are completely inaccessible outside a class.

The Modern Solution to Privacy

JavaScript finally has a native, bulletproof way to declare private class members: prefix them with #. Unlike underscore conventions or WeakMaps, fields declared with # are truly private at the language level—there's no way to access them from outside the class, not even through bracket notation or reflection tricks.

How It Works

class BankAccount {
  #balance = 0;  // Private field
  
  constructor(initialBalance) {
    this.#balance = initialBalance;
  }
  
  deposit(amount) {
    this.#balance += amount;
  }
  
  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.#balance);     // SyntaxError!

The # is part of the field's name—you must always use it when referencing the field inside the class. Attempting to access #balance from outside throws an error, not undefined.

Private Methods Too

class User {
  #password;
  
  constructor(pw) {
    this.#password = this.#hash(pw);
  }
  
  #hash(value) {  // Private method
    return value.split('').reverse().join('');
  }
}

const user = new User('secret');
user.#hash('test');  // SyntaxError!

Why This Matters

Unlike conventions or WeakMaps, # provides guaranteed encapsulation with clear syntax. The privacy is enforced by the JavaScript engine itself, making your intentions explicit and your code more secure.

Key Takeaway: The # prefix creates truly private class fields and methods that cannot be accessed outside the class—a native, bulletproof privacy mechanism built into modern JavaScript.