Private and static members
Overview
Classes usually have two kinds of member: the parts other code is meant to use (the public interface), and the inner workings it shouldn’t touch. JavaScript lets you mark the second kind as private, and lets you put some members on the class itself with static.
Private fields
Some details of a class are nobody else’s business. Prefix a field or method with # and it becomes private — code outside the class can’t read or change it.
class Counter {
#count = 0;
increment() {
this.#count++;
}
get value() {
return this.#count;
}
}
const c = new Counter();
c.increment();
c.value; // 1
c.#count; // SyntaxError — private
c.count; // undefined — #count and count are different namesPrivate fields protect your rules: nobody can set #count to -5 from outside. The only way to change it is through methods you wrote, which can check every change.
Private fields must be declared in the class body before use; you can’t create them on the fly in the constructor.
Why bother?
- Safety. Invariants such as “balance is never negative” can’t be broken by careless outside code.
- Freedom to change. Code outside can’t depend on private details, so you can rename or restructure them without breaking anything.
- Clear interfaces. Anyone reading the class can see at a glance what’s meant for them.
Private methods
Methods can be private too — useful for helpers that only make sense inside the class:
class Order {
#items = [];
add(item) {
this.#validate(item);
this.#items.push(item);
}
#validate(item) {
if (!item.price || item.price < 0) {
throw new Error(`Invalid price for ${item.name}`);
}
}
}Checking for a private field
#field in obj tells you whether an object was made by this class (and has the private field), without throwing:
class Point {
#x = 0;
static isPoint(obj) {
return #x in obj;
}
}The underscore convention
Before # existed (2022), developers marked “please don’t touch” properties with a leading underscore: this._count. That’s only a convention — the property is still fully public. You’ll see it in older code and libraries.
Static members
static puts a property or method on the class itself rather than on each instance. Use it for helpers and factories:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
static fromFahrenheit(f) {
return new Temperature((f - 32) * (5 / 9));
}
}
const t = Temperature.fromFahrenheit(98.6);You call static methods on the class (Temperature.fromFahrenheit), never on an instance. You’ve used many built-in statics already: Math.max, Array.isArray, Object.keys, Number.isNaN, Date.now.
Factory methods
Static methods that create instances are called factories. They’re handy when there are several ways to build an object, each with a clear name:
class Colour {
constructor(r, g, b) {
Object.assign(this, { r, g, b });
}
static fromHex(hex) {
const n = parseInt(hex.slice(1), 16);
return new Colour(n >> 16, (n >> 8) & 255, n & 255);
}
static black() {
return new Colour(0, 0, 0);
}
}
Colour.fromHex('#2d5bd7'); // Colour { r: 45, g: 91, b: 215 }Static fields
Static fields hold data shared by the whole class — constants, defaults or counters:
class User {
static #nextId = 1;
static ROLES = ['learner', 'editor', 'admin'];
constructor(name) {
this.id = User.#nextId++;
this.name = name;
}
}
new User('Asha').id; // 1
new User('Ravi').id; // 2
User.ROLES; // ['learner', 'editor', 'admin']Inside a static method, this refers to the class itself, so this.ROLES would also work there.
Putting it together
Private + getter is a common pattern: keep the data private, and expose only what callers should read.
class BankAccount {
static #count = 0;
#balance = 0;
#history = [];
constructor(owner) {
this.owner = owner;
BankAccount.#count++;
}
static get count() {
return BankAccount.#count;
}
deposit(amount) {
this.#change(amount);
}
withdraw(amount) {
if (amount > this.#balance) throw new Error('Insufficient funds');
this.#change(-amount);
}
#change(amount) {
this.#balance += amount;
this.#history.push({ amount, at: new Date() });
}
get balance() {
return this.#balance;
}
get history() {
return [...this.#history]; // a copy, so callers can't edit the real list
}
}The only ways to change the balance are deposit and withdraw, and every change is recorded. Returning a copy of the history keeps it read-only from outside.
A private balance
Write a Wallet class with a private #balance, a deposit(amount) method that rejects non-positive amounts, a balance getter, and a static fromRupees(r) that creates a wallet with that starting balance.
class Wallet {
// your code here
}
const w = Wallet.fromRupees(100);
w.deposit(50);
w.balance; // 150class Wallet {
#balance = 0;
static fromRupees(r) {
const wallet = new Wallet();
wallet.deposit(r);
return wallet;
}
deposit(amount) {
if (amount <= 0) throw new Error('Amount must be positive');
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}Summary
- Fields and methods starting with
#can only be used inside the class body. - Private members protect a class’s rules and let you change internals safely.
staticmembers belong to the class, not to instances — call them asClassName.method().- Static methods are good for factories and helpers; static fields for shared constants and counters.
- Getters expose read-only views of private data.