Private methods (#): hide class helpers (ES2022)
What you’ll learn
Section titled “What you’ll learn”- How to declare
#method(), privateget #x/set #xaccessors andstatic #method(). - When private methods are attached to an instance and why field initializers can call them.
- Why private methods cannot be reassigned, borrowed or overridden by a subclass.
- When a private method is the right tool and when a plain module function is simpler.
Summary
Section titled “Summary”TL;DR: a method or accessor whose name starts with # can only be called from code inside the class body that declares it. It is not on the prototype, so outside code cannot call, patch or even list it. Private methods are read-only: assigning to one throws a TypeError.
Private methods and accessors were standardized in ECMAScript 2022, alongside the private fields they usually work with. This page covers methods only; the # rules shared with fields (declaration, per-class scoping, #name in obj checks, proxies) are explained on Private fields.
The problem it solves
Section titled “The problem it solves”Before ES2022, internal helpers lived on the prototype with an underscore prefix. Any code could call them, and any code could replace them for every instance at once, which makes the helper part of your public contract whether you meant it or not.
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: helpers live on the prototype, so anyone can call or replace them.class LegacyInvoice { constructor(lines) { this.lines = lines; } _subtotal() { return this.lines.reduce((sum, line) => sum + line.cents, 0); } totalCents() { return this._subtotal(); }}LegacyInvoice.prototype._subtotal = () => 0; // a "patch" elsewhere in the appconsole.log(new LegacyInvoice([{ cents: 500 }]).totalCents());
// After: the helper is private and cannot be called or replaced from outside.class Invoice { #lines; constructor(lines) { this.#lines = lines; } #subtotal() { return this.#lines.reduce((sum, line) => sum + line.cents, 0); } totalCents() { return this.#subtotal(); }}console.log(new Invoice([{ cents: 500 }]).totalCents(), Object.getOwnPropertyNames(Invoice.prototype));Output:
0500 [ 'constructor', 'totalCents' ]The other pre-ES2022 option, a function at module scope that takes the instance as an argument, is still valid and sometimes better (see When to use it). It just cannot read private fields unless the class hands them over.
How it works
Section titled “How it works”// Fragment: the four formsclass Example { #helper() {} // private instance method get #value() {} // private getter set #value(v) {} // private setter (pair it with the getter of the same name) static #factory() {} // static private method, called as Example.#factory()}The semantics, from the ECMAScript specification and observable in any engine:
- Installed per instance, shared function. Private methods are not stored on the prototype. When an instance is created, the engine adds the class’s private methods and accessors to it before any field initializer runs, so a field such as
#label = this.#makeLabel()works. All instances share the same function object. - Not writable. Assigning to a private method throws. Assigning to a private accessor that has no setter, or reading one that has no getter, also throws.
- The receiver must have the brand. Calling a method with
thisset to an object the class did not construct (Shipment.prototype.pack.call({})) throws as soon as it touches a private member. - Getter and setter share one name.
get #weightKgandset #weightKgare the only allowed duplicate private name in a class body, and both must be static or both non-static. #constructoris forbidden, and private names cannot be computed or accessed with brackets.
class Shipment { #weightGrams = 0; #label = this.#makeLabel('new'); // private methods exist before fields are initialized
#makeLabel(state) { return `shipment:${state}`; } get #weightKg() { return this.#weightGrams / 1000; } set #weightKg(kg) { if (kg < 0) throw new RangeError('weight cannot be negative'); this.#weightGrams = Math.round(kg * 1000); } get #carrier() { return 'ground'; } static #isHeavy(kg) { return kg > 20; }
pack(kg) { this.#weightKg = kg; // runs the private setter return { label: this.#label, kg: this.#weightKg, heavy: Shipment.#isHeavy(this.#weightKg) }; } sameHelper(other) { return this.#makeLabel === other.#makeLabel; } breakMethod() { this.#makeLabel = () => 'hacked'; } breakGetter() { this.#carrier = 'air'; }}
const shipment = new Shipment();console.log(shipment.pack(25.5), shipment.sameHelper(new Shipment()));for (const name of ['breakMethod', 'breakGetter']) { try { shipment[name](); } catch (error) { console.log(`${name}: ${error.name}: ${error.message}`); }}try { Shipment.prototype.pack.call({}, 1);} catch (error) { console.log(`borrowed call: ${error.name}: ${error.message}`);}Output (error messages are V8’s wording):
{ label: 'shipment:new', kg: 25.5, heavy: true } truebreakMethod: TypeError: Private method '#makeLabel' is not writablebreakGetter: TypeError: '#carrier' was defined without a setterborrowed call: TypeError: Receiver must be an instance of class ShipmentNo overriding
Section titled “No overriding”Private names are lexically scoped, so a subclass that declares a #describe() of its own creates a second, unrelated method. Code in the base class keeps calling the base version:
class PriceRule { #describe() { return 'base rule'; } explain() { return this.#describe(); }}class HolidayRule extends PriceRule { #describe() { return 'holiday rule'; // a different, unrelated private method }}console.log(new HolidayRule().explain());Output: base rule. That is the point of privacy: subclasses cannot change a base class’s internal steps. If you want an extension hook (the template method pattern), it has to be a public method.
Realistic example
Section titled “Realistic example”OrdersPortal builds invoice text from validated lines. The public API is just addLine() and build(). Validation, the subtotal, tax lookup and money formatting are private, so they can be renamed, merged or rewritten without breaking any caller.
// invoice.mjs - OrdersPortal invoice builder with a small public API.export class InvoiceBuilder { static #TAX_RATES = new Map([['US-WA', 0.065], ['US-OR', 0], ['DE', 0.19]]);
#region; #lines = [];
constructor(region) { InvoiceBuilder.#taxRateFor(region); // validate early: throws for unknown regions this.#region = region; }
addLine(sku, unitCents, qty) { this.#lines.push(this.#validateLine({ sku, unitCents, qty })); return this; }
build() { const subtotal = this.#subtotalCents; const tax = Math.round(subtotal * InvoiceBuilder.#taxRateFor(this.#region)); const money = InvoiceBuilder.#money; return [ ...this.#lines.map((l) => `${l.sku.padEnd(8)} ${l.qty} x ${money(l.unitCents)}`), `Subtotal ${money(subtotal)}`, `Tax ${money(tax)}`, `Total ${money(subtotal + tax)}`, ].join('\n'); }
#validateLine(line) { if (!Number.isInteger(line.unitCents) || line.unitCents < 0) { throw new RangeError(`${line.sku}: price must be a whole number of cents`); } if (!Number.isInteger(line.qty) || line.qty < 1) { throw new RangeError(`${line.sku}: quantity must be at least 1`); } return Object.freeze({ ...line }); }
get #subtotalCents() { return this.#lines.reduce((sum, l) => sum + l.unitCents * l.qty, 0); }
static #taxRateFor(region) { const rate = InvoiceBuilder.#TAX_RATES.get(region); if (rate === undefined) throw new RangeError(`No tax rate for region ${region}`); return rate; }
static #money(cents) { return 'USD ' + (cents / 100).toFixed(2); }}
console.log(new InvoiceBuilder('US-WA').addLine('MUG-01', 1200, 2).addLine('TEE-07', 2500, 1).build());
for (const attempt of [ () => new InvoiceBuilder('MARS'), () => new InvoiceBuilder('DE').addLine('BAD-1', 9.99, 1),]) { try { attempt(); } catch (error) { console.log(`${error.name}: ${error.message}`); }}console.log(Object.getOwnPropertyNames(InvoiceBuilder.prototype));Output:
MUG-01 2 x USD 12.00TEE-07 1 x USD 25.00Subtotal USD 49.00Tax USD 3.19Total USD 52.19RangeError: No tax rate for region MARSRangeError: BAD-1: price must be a whole number of cents[ 'constructor', 'addLine', 'build' ]Two details are deliberate. The static helpers are always called as InvoiceBuilder.#taxRateFor(...), never this.#taxRateFor(...) (see the next section). And #money can be pulled out into a local variable because it does not use this; a private method that does use this must be called on the instance or bound first.
Common mistakes
Section titled “Common mistakes”- Calling static private methods through
this. In a static method,thisis whichever class the call went through.this.#helper()works forBase.run()but throwsTypeError: Receiver must be class BaseforChild.run()whenChild extends Base. Use the class name. - Expecting a subclass to override a private method. It cannot; see No overriding. Make the hook public, or pass a strategy function in.
- Passing a private method as a callback without binding.
items.map(this.#format)losesthis. Useitems.map((x) => this.#format(x)). - Trying to unit test private methods directly. There is no way to reach them from a test file, by design. Test through the public API, or move pure logic into an exported module function that you can test on its own.
- Unpaired accessors. A private getter without a setter makes
this.#x = valuethrow at run time; it is not a syntax error, so tests must exercise it. - Proxies. As with fields, a method that touches a private member throws when
thisis aProxyof the instance. See Private fields.
When to use it and when not to
Section titled “When to use it and when not to”| Option | Callable from outside? | Can use private fields? | Overridable? | Testable directly? |
|---|---|---|---|---|
_helper() on the prototype |
Yes | No (unless they are public) | Yes | Yes |
| Module-level function, not exported | No (outside the module) | Only if passed in | No | No |
| Exported module function | Yes | Only if passed in | No | Yes |
#helper() (ES2022) |
No | Yes | No | No |
Use a private method when the helper needs the instance’s private state or is clearly part of the class’s internals. Use a module function when the logic is pure (formatting, math, parsing): it is easier to test and reuse, and needs no this. Use a public method when subclasses are meant to customize the behavior.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data (@mdn/browser-compat-data 8.1.9), private methods and accessors (instance and static) are supported in Chrome 84, Edge 84, Firefox 90, Safari 15 (iOS 15), Node.js 14.6.0, Deno 1.0 and Bun 1.0. That is later than private fields in Chrome and Safari, so check your browser targets if you still support 2020-era versions.
TypeScript: with target ES2022 or later, private methods are emitted unchanged. With target ES2021 or lower, TypeScript 6.0 records each instance in a module-level WeakSet and turns each private method into a plain function plus a brand check.
Interview questions
Section titled “Interview questions”1. Where does a private method live at runtime?
Not on the prototype. The class keeps the method, and each instance gets a private entry pointing at that same shared function object when it is constructed. That is why it never appears in Object.getOwnPropertyNames(Class.prototype) and why a plain object cannot borrow it.
2. Can a field initializer call a private method?
Yes. Private methods and accessors are added to the instance before field initializers run, so #label = this.#makeLabel() is fine. A field initializer cannot read a private field declared later, though: that field has not been added yet, so the read throws a TypeError.
3. Why does this.#helper() in a static method fail when called through a subclass?
Static private methods exist only on the class that declared them. Called as Child.run(), this is Child, which does not have the private method, so the brand check fails with a TypeError. Referring to the declaring class by name avoids it.
4. How do you test logic that lives in a private method? Through the public behavior that uses it. If the logic is complex enough to need its own tests, that is a sign it is pure logic that belongs in a separately exported function.
5. Senior scenario: a base PaymentProcessor class in OrdersPortal has a fixed sequence (validate, authorize, capture, record) and partner teams subclass it to change authorization. How do you use private methods?
Make the fixed steps private (#validate, #record) so subclasses cannot skip or reorder them, and expose the sequence through one public, non-overridden method such as process(). Provide the variable step as an explicit extension point: a public or documented method like authorize() that subclasses override, or better, an injected authorizer object, which avoids inheritance entirely. Keep shared formatting or calculation helpers as module functions so they can be unit tested.
Key takeaways
Section titled “Key takeaways”#method(),get #x/set #xandstatic #method()(ES2022) are callable only inside the declaring class body.- They are added to each instance before fields are initialized, are read-only, and are not on the prototype.
- They cannot be overridden or borrowed; subclasses get a separate method with the same spelling.
- Call static private methods through the class name, not
this. - Prefer module functions for pure helpers you want to test and reuse.
Related pages
Section titled “Related pages”- Private fields:
#fields, brand checks and the shared privacy rules. - Static initialization blocks: run static setup that uses private members.
- Classes: class syntax, inheritance and
super. - Modules: module-scoped functions as an alternative to private helpers.
- The this keyword: why unbound callbacks lose
this.
Official references
Section titled “Official references”- ECMAScript Language Specification: Class Definitions and PrivateMethodOrAccessorAdd (current draft; first published in ECMAScript 2022, 13th edition)
- ECMAScript 2022 Language Specification (ECMA-262, 13th edition)
- TC39 proposal: Private methods and getter/setters
- TC39 proposal: Static class features
- MDN: Private elements