Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Private fields (#)

Fields and methods accessible only inside the class.

Available since: ES2022

Syntax

#field / #method() { … }

Examples

The balance cannot be changed from outside:

class BankAccount {
  #balance = 0;
 
  deposit(amount) {
    if (amount <= 0) throw new RangeError('Amount must be positive');
    this.#balance += amount;
  }
 
  get balance() {
    return this.#balance;
  }
}
 
const account = new BankAccount();
account.deposit(100);
 
console.log(account.balance);
console.log(account['#balance']);

Output:

100
undefined

Checking for a private field:

class Point {
  #x = 0;
 
  static isPoint(value) {
    return #x in value;
  }
}
 
console.log(Point.isPoint(new Point()), Point.isPoint({}));

Output:

true false

Notes

The hash is part of the name: #balance and balance are different fields. Accessing obj.#balance outside the class is a syntax error — the code will not even run.

See also

  • class — Declares a class — a template for objects with shared methods.
  • get / set — Properties backed by functions: reading calls get, writing calls set.
  • static — A method or property of the class itself, not of its objects.

In the tutorial

  • Private and static members — Private fields and methods of JavaScript classes with #, encapsulation, static methods and properties.

Thanks for reading!

Donate to the site — we work hard for you.