Static, Private and Accessor Members

Updated · 8 min read
hardES2026javascriptclassesprivate-fieldsstaticgetters-setters

Beyond constructors and ordinary methods, a class can declare static members that belong to the class itself rather than to instances, private members (names starting with #) that only the class's own code can touch, accessors (getters and setters) that run code when a property is read or written, and static initialization blocks for one-time setup. Together they let a class present a small, safe public interface and keep its internal details hidden.

In One Minute

  • static members belong to the class: Payment.fromJSON(data), Payment.count. Instances don't have them.
  • #name fields and #method()s are truly private: accessing them from outside the class is a SyntaxError.
  • #field in obj checks whether an object was created by this class (a "brand check").
  • get and set define accessor properties that look like fields but run code.
  • static { ... } blocks run once when the class is defined.

Static Members

A static member is attached to the class (the constructor function), not to its instances. Use static methods for factory functions and helpers that relate to the class but don't need a particular instance:

static.js▶ Try it
class Payment {
  static count = 0;
  static CURRENCY = "USD";
 
  constructor(name, amount) {
    this.name = name;
    this.amount = amount;
    Payment.count++;
  }
 
  static fromJSON(json) {
    const { name, amount } = JSON.parse(json);
    return new Payment(name, amount);
  }
 
  static compareByAmount(a, b) {
    return a.amount - b.amount;
  }
}
 
const list = [new Payment("Navika", 120), Payment.fromJSON('{"name":"Advitha","amount":45}')];
console.log(Payment.count, Payment.CURRENCY);
console.log(list.toSorted(Payment.compareByAmount).map((p) => p.name));
console.log(list[0].count, typeof list[0].fromJSON);
Output
2 USD
['Advitha', 'Navika']
undefined undefined

Explanation: Payment.count and Payment.CURRENCY are properties of the class. fromJSON is an alternative constructor, a common use of static methods. compareByAmount doesn't use this, so it can be passed straight to toSorted. Instances don't see static members at all.

Built-in examples of static methods: Array.from, Object.keys, Number.isInteger, Promise.all, Temporal.PlainDate.from.

Inside a static method, this is the class itself (when called as Payment.method()), and static members are inherited by subclasses through extends.

Private Fields and Methods

A private member's name starts with #. It can only be used inside the class body; any attempt from outside is a syntax error, caught before the code even runs:

private.js▶ Try it
class Account {
  #balance;
  #history = [];
 
  constructor(owner, opening) {
    this.owner = owner;
    this.#balance = opening;
  }
 
  pay(amount) {
    this.#validate(amount);
    this.#balance -= amount;
    this.#history.push(-amount);
    return this;
  }
 
  #validate(amount) {
    if (!(amount > 0)) throw new RangeError("Payment must be positive");
    if (amount > this.#balance) throw new RangeError(`Only $${this.#balance} is due`);
  }
 
  get balance() {
    return this.#balance;
  }
}
 
const account = new Account("Srihitha", 450);
account.pay(200);
console.log(account.balance);
console.log(Object.keys(account), JSON.stringify(account));
console.log(account["#balance"]);
 
try {
  account.pay(500);
} catch (err) {
  console.log(err.message);
}
Output
250
['owner'] {"owner":"Srihitha"}
undefined
Only $250 is due

Explanation: #balance, #history and #validate are invisible from outside: they don't appear in Object.keys, JSON.stringify or for...in, and account["#balance"] reads an ordinary (non-existent) property named "#balance", not the private field. Writing account.#balance anywhere outside the class body would be a SyntaxError. The only way to change the balance is through pay, which validates its input.

Public propertySymbol key#private
Readable from outsideYesYes, with the symbol or getOwnPropertySymbolsNo
Shown by Object.keys, JSONYesNoNo
Enforced byNothingConventionThe language itself
Subclasses can use itYesYesNo (only the declaring class)

Before #private (ES2022), JavaScript used a leading underscore (this._balance) as a convention meaning "please don't touch", or closures and WeakMaps for real privacy. You'll still see underscores in older code; they hide nothing.

Brand Checks with #field in obj

Private names also give a reliable way to check whether an object was created by your class, even if someone faked its prototype:

brand.js▶ Try it
class Receipt {
  #id;
  constructor(id) { this.#id = id; }
  static isReceipt(value) {
    return typeof value === "object" && value !== null && #id in value;
  }
}
 
const real = new Receipt(42);
const fake = Object.create(Receipt.prototype);
 
console.log(Receipt.isReceipt(real), real instanceof Receipt);
console.log(Receipt.isReceipt(fake), fake instanceof Receipt);
Output
true true
false true

instanceof only checks the prototype chain, which can be faked; #id in value checks whether the class's constructor actually ran on that object.

Getters and Setters

An accessor property looks like a normal property from outside, but reading it calls a getter and assigning it calls a setter:

accessors.js▶ Try it
class Student {
  #grade;
 
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }
 
  get grade() {
    return this.#grade;
  }
 
  set grade(value) {
    if (!Number.isInteger(value) || value < 1 || value > 12) {
      throw new RangeError(`Grade must be 1 to 12, got ${value}`);
    }
    this.#grade = value;
  }
 
  get label() {
    return `${this.name} (grade ${this.#grade})`;
  }
}
 
const s = new Student("Advitha", 9);
s.grade = 10;
console.log(s.label);
 
try {
  s.grade = 15;
} catch (err) {
  console.log(err.message);
}
console.log(s.grade);
Output
Advitha (grade 10)
Grade must be 1 to 12, got 15
10

Explanation: the constructor's this.grade = grade already goes through the setter, so validation runs on creation too. The rejected assignment left the grade unchanged. label has a getter but no setter, so it is read-only (assigning to it is ignored in sloppy mode and throws in strict mode, including inside classes).

Use a getter forUse a setter for
Values computed from other data (balance, label)Validating or normalizing input
Read-only access to private stateKeeping related data in sync
Lazy values computed on first readLogging or notifying on change

Static Initialization Blocks

A static { ... } block runs once, when the class is defined, with this set to the class. Use it for setup that needs statements, not just a single expression:

static-block.js▶ Try it
class FeeSchedule {
  static #fees = new Map();
  static grades;
 
  static {
    for (let grade = 9; grade <= 12; grade++) {
      this.#fees.set(grade, 400 + (grade - 9) * 15);
    }
    this.grades = [...this.#fees.keys()];
  }
 
  static feeFor(grade) {
    return this.#fees.get(grade) ?? null;
  }
}
 
console.log(FeeSchedule.grades);
console.log(FeeSchedule.feeFor(11), FeeSchedule.feeFor(8));
Output
[9, 10, 11, 12]
430 null

Static private fields (static #fees) combine both ideas: one hidden value shared by the class, reachable only by its own static code.

In Practice

The Fee Tracker's Invoice class uses every kind of member: a static counter and factory, private state, a validated setter, computed getters, and a static block that loads configuration:

invoice.js▶ Try it
class Invoice {
  static #nextNumber;
  static TAX_RATE;
  static {
    this.#nextNumber = 1001;
    this.TAX_RATE = 0.0825;
  }
 
  #number;
  #lines = [];
  #status = "draft";
 
  constructor(student) {
    this.student = student;
    this.#number = Invoice.#nextNumber++;
  }
 
  static forStudent(student, items) {
    const invoice = new Invoice(student);
    for (const [label, amount] of items) invoice.addLine(label, amount);
    return invoice;
  }
 
  addLine(label, amount) {
    if (this.#status !== "draft") throw new Error("Invoice is already sent");
    this.#lines.push({ label, amount });
  }
 
  set status(value) {
    if (!["draft", "sent", "paid"].includes(value)) throw new RangeError(`Unknown status ${value}`);
    this.#status = value;
  }
  get status() { return this.#status; }
 
  get subtotal() { return this.#lines.reduce((s, l) => s + l.amount, 0); }
  get total() { return Math.round(this.subtotal * (1 + Invoice.TAX_RATE) * 100) / 100; }
  get number() { return `INV-${this.#number}`; }
}
 
const inv = Invoice.forStudent("Navika", [["Books", 85], ["Lab kit", 45]]);
inv.status = "sent";
console.log(inv.number, inv.status, inv.subtotal, inv.total);
try {
  inv.addLine("Bus", 30);
} catch (err) {
  console.log(err.message);
}
console.log(Invoice.forStudent("Advitha", [["Uniform", 60]]).number);
Output
INV-1001 sent 130 140.73
Invoice is already sent
INV-1002

Common Mistakes

Expecting instances to have static members. invoice.TAX_RATE is undefined; use Invoice.TAX_RATE.

Using underscores for privacy. _balance is still public. Use #balance.

Accessing #private members from a subclass. Only the declaring class can; expose a protected-style getter if subclasses need it.

A getter and a data property with the same name. get grade() plus this.grade = ... without a setter makes the assignment fail. Store the value in a private field.

Practice

Challenge: Write a Temperature class that stores Celsius in a private field, with a fahrenheit getter and setter (F = C × 9/5 + 32), and a static fromFahrenheit(f) factory.

Show solution
temperature.js▶ Try it
class Temperature {
  #celsius;
  constructor(celsius) { this.#celsius = celsius; }
  get celsius() { return this.#celsius; }
  get fahrenheit() { return (this.#celsius * 9) / 5 + 32; }
  set fahrenheit(f) { this.#celsius = ((f - 32) * 5) / 9; }
  static fromFahrenheit(f) { return new Temperature(((f - 32) * 5) / 9); }
}
 
const t = new Temperature(25);
console.log(t.fahrenheit);
t.fahrenheit = 212;
console.log(t.celsius);
console.log(Temperature.fromFahrenheit(32).celsius);
Output
77
100
0

Quick check: Class members

3 questions
1Where does a static method live?
2What happens when code outside a class writes obj.#balance?
3What does a getter without a setter create?

Key Takeaways

MemberSyntax
Static methodstatic fromJSON(json) { ... }
Static fieldstatic count = 0;
Private field#balance = 0;
Private method#validate(x) { ... }
Brand check#balance in obj
Getter / setterget grade() { ... } / set grade(v) { ... }
Static blockstatic { ... }

Was this tutorial helpful?

Lesson 99 of 139