Class static blocks: one-time class setup (ES2022)
What you’ll learn
Section titled “What you’ll learn”- What a
static { ... }block is and exactly when it runs. - How blocks interleave with static fields, and what
thisandsupermean inside them. - How a static block can share private access with code outside the class.
- Which statements are not allowed inside a block, and when not to use one.
Summary
Section titled “Summary”TL;DR: a class static initialization block is a static { ... } section in a class body. Its statements run once, while the class is being defined, with this bound to the class. Unlike code after the class, it can read and write the class’s private names.
Static blocks were added in ECMAScript 2022 and work in every current browser and server runtime (see Compatibility).
The problem it solves
Section titled “The problem it solves”Static fields take a single expression. Multi-statement setup (building a lookup table, validating configuration, try...catch fallbacks) used to go after the class or into an immediately invoked function in a field initializer. Code after the class cannot touch #private state at all.
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.
const RATE_ROWS = [ ['US', 'ground', 599], ['US', 'express', 1499], ['CA', 'ground', 899],];
// Before: setup runs after the class, outside its body, and cannot touch #private state.class LegacyRates { static table = new Map();}for (const [country, speed, cents] of RATE_ROWS) { LegacyRates.table.set(`${country}:${speed}`, cents);}
// After: the setup is part of the class definition and can use private names.class ShippingRates { static #table = new Map(); static countries;
static { for (const [country, speed, cents] of RATE_ROWS) { this.#table.set(`${country}:${speed}`, cents); // `this` is ShippingRates } this.countries = [...new Set(RATE_ROWS.map(([country]) => country))]; }
static priceCents(country, speed) { return ShippingRates.#table.get(`${country}:${speed}`); }}
console.log(LegacyRates.table.size, ShippingRates.countries, ShippingRates.priceCents('US', 'express'));Output:
3 [ 'US', 'CA' ] 1499How it works
Section titled “How it works”- When it runs: once, during class definition evaluation, after the methods are created and the class’s inner name binding is initialized, but before the class is returned to the surrounding code. A class declaration at module top level therefore runs its blocks when the module is evaluated; a class expression inside a function runs them every time the function creates the class.
- Order: static fields and static blocks run together, top to bottom, in source order. A class can have any number of blocks.
thisis the class constructor, andsuper.propreads static members of the parent class.- Scope: the block is its own scope.
var,let,constand function declarations inside it do not leak out. - Errors: an exception thrown in a block propagates out of the class definition, so the class binding is never initialized.
const log = [];class Demo { static a = log.push('field a'); static { log.push('block 1, this === Demo: ' + (this === Demo)); } static b = log.push('field b'); static { var scoped = 1; log.push('block 2'); }}console.log(log, typeof scoped);
class Parent { static greet() { return 'parent'; } }class Kid extends Parent { static { console.log('super.greet():', super.greet()); } }
try { class Broken { static { throw new Error('bad config'); } }} catch (e) { console.log('class definition failed:', e.message);}Output:
[ 'field a', 'block 1, this === Demo: true', 'field b', 'block 2' ] undefinedsuper.greet(): parentclass definition failed: bad configWhat is not allowed
Section titled “What is not allowed”The block body behaves like a method body with extra early errors from the specification. Each of these is a SyntaxError when the file is parsed (messages from Node.js 22):
Inside static { } |
Node.js 22 error |
|---|---|
return |
Illegal return statement |
arguments |
'arguments' is not allowed in class field initializer or static initialization block |
await (even inside an async function) |
Unexpected reserved word |
super() |
'super' keyword unexpected here |
Because await is forbidden, a static block cannot wait for asynchronous setup. Start the work and store the promise in a static field, or do async initialization in a separate init() function.
Realistic example
Section titled “Realistic example”OrdersPortal represents order states as one frozen instance per status code. The static block validates the transition table, so a typo fails when the module is imported rather than on the first order that hits it. It also uses the “friend” pattern from the TC39 proposal: it assigns a module-level function that can read a private field, giving auditReport() access without making the field public.
// order-status.mjs - OrdersPortal order states, built once when the class is defined.let readAuditTrail; // "friend" access, assigned inside the static block
export class OrderStatus { static #byCode = new Map(); static #transitions = { placed: ['paid', 'cancelled'], paid: ['shipped', 'refunded'], shipped: ['delivered'], delivered: [], cancelled: [], refunded: [], };
#code; #audit = [];
constructor(code) { this.#code = code; }
static { // 1. Validate the configuration: fail at import time, not on the first order. const codes = Object.keys(this.#transitions); for (const [from, targets] of Object.entries(this.#transitions)) { for (const to of targets) { if (!codes.includes(to)) throw new Error(`Unknown transition ${from} -> ${to}`); } } // 2. Create one frozen instance per code. for (const code of codes) this.#byCode.set(code, Object.freeze(new OrderStatus(code))); // 3. Share private access with module code without making it public. readAuditTrail = (status) => [...status.#audit]; }
static from(code) { const status = OrderStatus.#byCode.get(code); if (!status) throw new RangeError(`Unknown order status "${code}"`); return status; }
canMoveTo(next) { return OrderStatus.#transitions[this.#code].includes(next.#code); }
recordCheck(next) { this.#audit.push(`${this.#code}->${next.#code}:${this.canMoveTo(next)}`); }
toString() { return this.#code; }}
export function auditReport(status) { return `${status}: ${readAuditTrail(status).join(', ') || 'no checks'}`;}
const paid = OrderStatus.from('paid');paid.recordCheck(OrderStatus.from('shipped'));paid.recordCheck(OrderStatus.from('delivered'));console.log(String(paid), Object.isFrozen(paid), OrderStatus.from('paid') === paid);console.log(auditReport(paid));try { OrderStatus.from('lost');} catch (error) { console.log(`${error.name}: ${error.message}`);}Output:
paid true truepaid: paid->shipped:true, paid->delivered:falseRangeError: Unknown order status "lost"The block can call new OrderStatus(...) because the class’s inner name binding is already initialized when static elements run. Freezing an instance does not stop class code from using its private fields, which is why #audit still works.
Common mistakes
Section titled “Common mistakes”- Reading a static field declared further down. Fields and blocks run in source order, so a block placed above
static #table = new Map()sees#tableas not yet added and throws. Put the block after the fields it uses. - Doing slow or side-effectful work. Blocks run at import time; I/O or heavy computation there slows every import and makes tests order-dependent.
- Expecting async setup.
awaitis a syntax error. Store a promise or use an explicit init function. - Expecting subclasses to re-run the block. A block runs only for the class that contains it.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Best tool |
|---|---|
| One static value from one expression | A static field: static rates = new Map(ROWS) |
Multi-statement setup, try...catch, several fields from one computation |
A static block |
Setup that must read or write #private static or instance state |
A static block |
| Sharing private access with module-level helpers or tests | A static block assigning a module variable (the “friend” pattern) |
| Async initialization or anything with I/O | An explicit init() function or top-level await in the module |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data (@mdn/browser-compat-data 8.1.9), static initialization blocks are supported in Chrome 94, Edge 94, Firefox 93, Safari 16.4 (iOS 16.4), Node.js 16.11.0, Deno 1.14 and Bun 1.0. Safari support arrived later than the other engines, so check older iOS targets. TypeScript has parsed static blocks since 4.4; with target ES2021 or lower, TypeScript 6.0 emits each block as an immediately invoked function that runs right after the class is created.
Interview questions
Section titled “Interview questions”1. When does a static block run, and how many times? Once per evaluation of the class definition, during that evaluation and in source order with static fields. For a top-level class declaration that is once, when the module is evaluated.
2. What can a static block do that code after the class cannot? It can access the class’s private names, including static and instance private fields and methods. Code after the class body cannot reach them at all.
3. Senior scenario: an OrdersPortal pricing class needs a rates table that is validated once, and the reporting module needs read access to private totals without exposing them publicly. How do you design it?
Build and validate the rates table in a static block placed after the private static fields it fills, throwing on bad data so a broken deployment fails at import. For reporting, use the friend pattern: declare let readTotals; at module scope, assign readTotals = (p) => p.#totals in the static block, and export only a reporting function that uses it. If the rates come from a service rather than from code, do not fetch them in the block; load them in an async init() and pass them in.
Key takeaways
Section titled “Key takeaways”static { }(ES2022) runs once while the class is defined, in source order with static fields, withthisas the class.- It can use private names, which makes it the place for setup that touches
#privatestate and for the friend-access pattern. return,arguments,awaitandsuper()are syntax errors inside it.- Keep blocks fast, synchronous and deterministic; prefer a plain static field for one-expression values.
Related pages
Section titled “Related pages”- Private fields: the
#fields that static blocks often initialize. - Private methods: private helpers a static block can call.
- Classes: class syntax, static members and inheritance.
- Top-level await: the module-level alternative for asynchronous setup.
- Modules: when module code runs on import.
Official references
Section titled “Official references”- ECMAScript Language Specification: Class Definitions,
ClassStaticBlock(current draft; first published in ECMAScript 2022, 13th edition) - ECMAScript 2022 Language Specification (ECMA-262, 13th edition)
- TC39 proposal: Class static initialization blocks
- MDN: Static initialization blocks