🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Private Class Fields

A private class field is a field that only code inside the class can read or change. Its name starts with a hash sign, like #balance.

Declare a private field

The #balance field is declared inside the class body. Only methods of this class can touch it.

class BankAccount {
  #balance = 100;

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

Read a private field through a method

getBalance runs inside the class, so it can read #balance. The code outside calls the method, not the field.

class BankAccount {
  #balance = 100;

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

const account = new BankAccount();
console.log(account.getBalance());

Change a private field through a method

deposit runs inside the class, so it can change #balance. The balance grows from 100 to 150.

class BankAccount {
  #balance = 100;

  deposit(amount) {
    this.#balance = this.#balance + amount;
  }

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

const account = new BankAccount();
account.deposit(50);
console.log(account.getBalance());

Outside access is an error

The bad read runs through eval, so the error can be caught. The error name is SyntaxError, and the method still works after it.

class BankAccount {
  #balance = 100;

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

const account = new BankAccount();
try {
  eval("account.#balance");
} catch (err) {
  console.log(err.name);
}
console.log(account.getBalance());

Example

class Safe {
  #code = 1234;

  open(guess) {
    if (guess === this.#code) {
      return "Safe open";
    }
    return "Wrong code";
  }
}

const safe = new Safe();
console.log(safe.open(1111));
console.log(safe.open(1234));

Key points

  • Private field: a field that code outside the class cannot reach
  • A private field name starts with # with the name right after it.
  • A method inside the class can read and change a private field.
  • Code outside the class cannot read a private field, even through the instance.
  • Reading a private field outside the class throws a SyntaxError.
  • eval: a function that runs a piece of text as code, so an error in that text can be caught
  • A public method can hand out a private value under its own rules, like returning a balance.

In this example, the Safe class keeps its code in a private field. The open method checks each guess against the hidden code. A wrong guess is refused, and the right guess opens the safe.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What happens when code outside a class reads a #field?