Skip to content

Private class fields (#): real encapsulation (ES2022)

  • How to declare and use instance and static private fields with the # prefix.
  • What “hard privacy” means: which tools can and cannot see a private field.
  • How the #field in obj brand check replaces instanceof for trusted checks.
  • The two common traps: Proxy wrappers and static private fields reached through a subclass.
  • How #private compares with underscores, closures, WeakMap and TypeScript’s private.

TL;DR: a class field whose name starts with # (for example #items) can only be read or written by code written inside that class body. It does not appear in Object.keys(), JSON.stringify(), Reflect.ownKeys() or structuredClone(), and outside code cannot reach it by any means. Reading it from an object that lacks it throws a TypeError.

Private fields were standardized in ECMAScript 2022 together with public class fields, private methods and static class features. Every current browser and server runtime supports them (see Compatibility). Private methods and accessors have their own page: Private methods.

Before ES2022, teams marked internal state with a leading underscore, which is only a convention: anything can read or change _items, and serializers include it.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23.

// Before: an underscore is only a naming convention.
class LegacyCart {
constructor() {
this._items = [];
}
add(sku, priceCents) {
this._items.push({ sku, priceCents });
}
get totalCents() {
return this._items.reduce((sum, item) => sum + item.priceCents, 0);
}
}
const legacy = new LegacyCart();
legacy.add('SKU-1', 1999);
legacy._items.push({ sku: 'FREE', priceCents: -1999 }); // nothing stops this
console.log(legacy.totalCents, Object.keys(legacy), JSON.stringify(legacy));
// After: #items is reachable only from code inside the class body.
class Cart {
#items = [];
add(sku, priceCents) {
this.#items.push({ sku, priceCents });
}
get totalCents() {
return this.#items.reduce((sum, item) => sum + item.priceCents, 0);
}
}
const cart = new Cart();
cart.add('SKU-1', 1999);
cart['#items'] = []; // creates an unrelated public property named "#items"
console.log(cart.totalCents, Object.keys(cart), JSON.stringify(cart));

Output:

0 [ '_items' ] {"_items":[{"sku":"SKU-1","priceCents":1999},{"sku":"FREE","priceCents":-1999}]}
1999 [ '#items' ] {"#items":[]}

The real alternatives were closures and a module-level WeakMap keyed by instance (compared in When to use it). Private fields give the WeakMap semantics with ordinary class syntax.

// Fragment: the syntax
class Example {
#count = 0; // instance private field with an initializer
#name; // declared, starts as undefined
static #instances = 0; // static private field, stored on the class itself
method(other) {
this.#count += 1; // read and write with this.#name
return other.#count; // any instance of this class, not only `this`
}
}

The rules:

  • Declare before use. Every #name must be declared in the class body. Referring to an undeclared one is a SyntaxError when the script is parsed: Private field '#nope' must be declared in an enclosing class.
  • No dynamic access. There is no this['#count'] or this[name] form; #count is part of the syntax, not a string. delete this.#count is also a SyntaxError.
  • Added at construction. Fields are installed on each new instance when the constructor runs (for a subclass, right after super() returns). An object that did not go through the constructor does not have them, so reading or writing one throws a TypeError. Adding the same private field twice to one object also throws.
  • Lexically scoped, per class. Two classes that both declare #status have unrelated names; functions and classes nested inside the body can use the outer class’s names.
  • Invisible to reflection. Private fields are not properties, so Object.keys, Reflect.ownKeys, for...in, JSON.stringify and structuredClone ignore them. Node.js 22’s console.log omits them; browser DevTools show them.
  • Optional chaining works: obj?.#count is valid inside the class.
class Order {
#status = 'draft';
static #nextId = 1;
id = Order.#nextId++;
static readStatus(value) {
return value.#status; // works for any object that has this class's #status
}
}
const order = new Order();
console.log(Object.keys(order), Reflect.ownKeys(order), structuredClone(order));
console.log(Order.readStatus(order));
const attempts = {
'plain object': () => Order.readStatus({ status: 'draft' }),
proxy: () => Order.readStatus(new Proxy(order, {})),
};
for (const [label, run] of Object.entries(attempts)) {
try {
run();
} catch (error) {
console.log(`${label}: ${error.name}: ${error.message}`);
}
}
// Each class creates its own private names, even if the spelling matches.
class Shipment {
#status = 'packed';
}
try {
Order.readStatus(new Shipment());
} catch (error) {
console.log(`Shipment: ${error.name}`);
}

Output:

[ 'id' ] [ 'id' ] { id: 1 }
draft
plain object: TypeError: Cannot read private member #status from an object whose class did not declare it
proxy: TypeError: Cannot read private member #status from an object whose class did not declare it
Shipment: TypeError

The proxy case surprises people: a Proxy is a different object from its target, and private access never goes through traps, so the lookup fails on the proxy. The same happens when a method is called through the proxy, because this is then the proxy.

The ergonomic brand checks proposal, also part of ES2022, lets #name in value test whether an object has that private field without throwing. Unlike instanceof, it cannot be fooled by Object.setPrototypeOf or Symbol.hasInstance, and it is false for objects from look-alike classes. The left side must be a private name declared in an enclosing class, and the right side must be an object, otherwise in throws a TypeError.

OrdersPortal keeps a shopping cart whose lines and currency must only change through methods that validate input. A guest cart is merged into the account cart at sign-in. mergeFrom() reads the other cart’s private fields, which is allowed because the code is inside the Cart class, and uses a brand check to reject look-alike objects.

// cart.mjs - an OrdersPortal shopping cart with private state.
export class Cart {
#currency;
#lines = new Map(); // sku -> { priceCents, qty }
static #created = 0;
constructor(currency = 'USD') {
this.#currency = currency;
Cart.#created += 1; // use the class name, not `this`, for static private fields
}
static get created() {
return Cart.#created;
}
static isCart(value) {
return #lines in value; // brand check: true only for real Cart instances
}
add(sku, priceCents, qty = 1) {
if (!Number.isInteger(qty) || qty < 1) {
throw new RangeError(`Invalid quantity ${qty} for ${sku}`);
}
const line = this.#lines.get(sku) ?? { priceCents, qty: 0 };
line.qty += qty;
this.#lines.set(sku, line);
return this;
}
get totalCents() {
let total = 0;
for (const { priceCents, qty } of this.#lines.values()) total += priceCents * qty;
return total;
}
mergeFrom(other) {
if (!Cart.isCart(other)) throw new TypeError('mergeFrom() expects a Cart');
if (other.#currency !== this.#currency) {
throw new TypeError(`Cannot merge ${other.#currency} into ${this.#currency}`);
}
// Code inside the class can read another instance's private fields.
for (const [sku, { priceCents, qty }] of other.#lines) this.add(sku, priceCents, qty);
return this;
}
toJSON() {
const items = [...this.#lines].map(([sku, line]) => ({ sku, ...line }));
return { currency: this.#currency, items, totalCents: this.totalCents };
}
}
const guestCart = new Cart().add('MUG-01', 1200, 2);
const accountCart = new Cart().add('TEE-07', 2500).mergeFrom(guestCart);
console.log(JSON.stringify(accountCart));
console.log(Cart.isCart(accountCart), Cart.isCart({ lines: [] }), Cart.created);
for (const attempt of [
() => accountCart.mergeFrom({ currency: 'USD', lines: new Map() }),
() => accountCart.mergeFrom(new Cart('EUR')),
() => accountCart.add('MUG-01', 1200, 0),
]) {
try {
attempt();
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
}

Output:

{"currency":"USD","items":[{"sku":"TEE-07","priceCents":2500,"qty":1},{"sku":"MUG-01","priceCents":1200,"qty":2}],"totalCents":4900}
true false 2
TypeError: mergeFrom() expects a Cart
TypeError: Cannot merge EUR into USD
RangeError: Invalid quantity 0 for MUG-01

Because private fields are hidden from JSON.stringify, toJSON() decides exactly what is serialized, so a new private field can never leak into an API response.

  • Wrapping instances in a Proxy. Reactive stores and logging wrappers often return proxies, and any method that touches this.#field then throws. Keep such classes out of proxy-based stores, or bind methods to the target in the get trap.

  • Static private fields through this in a subclass. this.#count in a static method fails when the method is called as SubClass.method(), because the field lives only on the base class:

    class Counter {
    static #count = 0;
    static increment() {
    return ++this.#count; // `this` is whatever class the method was called on
    }
    }
    class OrderCounter extends Counter {}
    console.log(Counter.increment());
    try {
    OrderCounter.increment();
    } catch (error) {
    console.log(`${error.name}: ${error.message}`);
    }

    Output: 1, then TypeError: Cannot read private member #count from an object whose class did not declare it. Write Counter.#count instead.

  • Expecting subclasses to see the field. A subclass instance has the base class’s #items, but subclass code cannot name it. JavaScript has no protected; keep the logic in the base class or expose an accessor.

  • Using instanceof as a security check. It follows the prototype chain, which any code can change. Use #field in value when the check guards private data.

  • Leaking the internal object. A method that returns this.#lines hands out a mutable reference. Return copies ([...this.#lines]).

  • Relying on Object.freeze to block them. Freezing an instance does not stop class code from writing its private fields. In today’s engines, a base class constructor that returns some other object (the “return override” trick) can even add a subclass’s private fields to a frozen object. The stage 3 proposal Non-extensible Applies to Private would make that throw; it is not part of any published edition yet.

Technique Truly private? Works with JSON/Object.keys Notes
_name convention No Included Fine for internal code where you trust every caller
Closure variables in the constructor Yes Hidden One function per method per instance; not shared across instances
Module-level WeakMap keyed by instance Yes Hidden What transpilers emit for # below ES2022
Symbol keys No Hidden from Object.keys, visible to Reflect.ownKeys Avoids name clashes, not access
#name (ES2022) Yes Hidden Per-class scoping; breaks behind a Proxy
TypeScript private Compile time only Included Erased at runtime; obj['name'] and plain JavaScript callers bypass it

Use private fields for state guarded by invariants (totals, caches, tokens) and in library classes whose internals must stay free to change. Prefer public or _-prefixed fields when frameworks must reach the state (reactive proxies, serializers, instance patching) or subclasses need it.

According to MDN’s browser compatibility data (@mdn/browser-compat-data 8.1.9), private class fields are supported in Chrome 74, Edge 79, Firefox 90, Safari 14.1 (iOS 14.5), Node.js 12.0.0, Deno 1.0 and Bun 1.0. The #field in obj brand check needs Chrome 91, Edge 91, Firefox 90, Safari 15, Node.js 16.4.0 and Deno 1.9.

TypeScript: with target ES2022 or later, #name is emitted unchanged. With target ES2021 or lower, TypeScript 6.0 rewrites each private field into a module-level WeakMap plus __classPrivateFieldGet/__classPrivateFieldSet helpers. The emulation keeps the privacy and the TypeErrors, but it is slower and larger than native fields.

1. How is #count different from TypeScript’s private count? #count is enforced by the engine at runtime and is invisible to reflection and serialization. TypeScript’s private is erased during compilation, so at runtime it is a normal property that plain JavaScript callers, obj['count'] and JSON.stringify all see.

2. Can one instance read another instance’s private field? Yes. Privacy is per class, not per instance: code in the class body can read other.#field if other was constructed by that class or a subclass. That is what makes equals() and mergeFrom() possible.

3. Why does a method that uses this.#x throw when called through a Proxy? Private field lookup checks the private elements of the exact object, and a proxy is a different object with no private elements. Proxy traps are never consulted for private names, so the lookup fails with a TypeError.

4. What does #field in obj give you over instanceof? It tests whether the object actually carries the private field, so it cannot be spoofed with Object.setPrototypeOf or Symbol.hasInstance, and it never throws for an object that lacks the field. It is the safe guard before reading obj.#field.

5. Senior scenario: a shared OrdersPortal SDK class stores an access token and a retry counter. Some teams wrap SDK instances in a proxy-based state store. How do you design the class? Keep the token and counter in private fields so they cannot be logged, serialized or changed by callers, and expose behavior (request()) rather than the token. Because proxies break this.#token, document that instances must not be wrapped and give state stores a plain-data snapshot (toJSON()) instead. Use #token in value in static helpers that accept instances. For old runtimes, compile below ES2022 and accept the WeakMap emulation.

  • #name fields (ES2022) are truly private: only code in the declaring class body can access them.
  • Privacy is per class, not per instance; reflection and serialization never see the fields.
  • Reading a private field from an object that lacks it throws; check with #name in obj.
  • Proxies and this.#field in inherited static methods are the common runtime failures.
  • TypeScript’s private is compile-time only; # is enforced at runtime.
  • Private methods: #method(), private getters and setters, and static private methods.
  • Static initialization blocks: set up static private fields with multi-statement logic.
  • Classes: the class syntax that private fields extend.
  • WeakMap and WeakSet: the pre-ES2022 way to attach private data to objects.
  • Proxy: why proxies and private fields do not mix.
  • Reflect API: what reflection can and cannot see.
  • Objects: properties, enumeration and serialization basics.