Course contentsShow
← JavaScript
Lesson 1984 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Private Field Syntax with #

Using the # prefix to declare private fields that are inaccessible outside the class.

Private Field Syntax with

What you'll learn: How to use the # prefix to create truly private class fields that are completely inaccessible outside the class.

The Core Idea

In JavaScript classes, prefixing a field name with # makes it genuinely private—it cannot be accessed, read, or modified from outside the class. Unlike convention-based "privacy" (like naming something _internal), the # syntax is enforced by the language itself. Attempting to access a #field from outside the class causes a syntax error.

How It Works

You declare private fields at the top of your class body, before the constructor:

class BankAccount {
  #balance = 0;  // Private field declaration

  deposit(amount) {
    this.#balance += amount;  // Access inside class: ✓
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance());  // 100
console.log(account.#balance);      // SyntaxError: Private field '#balance' must be declared in an enclosing class

The # is part of the field name—you must always use it when referencing the field inside your class methods. It's not just a marker; #balance and balance are completely different identifiers.

Why It Matters

This creates real encapsulation. Your class can maintain internal state that consumers cannot accidentally (or intentionally) corrupt. It's like having a locked safe: you can only interact through the methods you've explicitly provided.

Key Takeaway: The # prefix creates truly private class fields that are language-enforced and completely inaccessible outside the class—use #fieldName both when declaring and accessing private fields internally.