JavaScript Static Class Members and Blocks
Quick answer
Static members belong to the class constructor object, not to its instance prototype. Static initialization blocks run during class evaluation.
How it works
Use static field = value, static method() { ... } and static { ... }. Static fields and blocks initialize in their textual order after methods are installed. In a static method call, this normally denotes the constructor receiver. Static methods can provide factory or utility operations. Public static fields are own properties of the defining constructor.
class Scale { static factor = 3; static convert(n) { return n * this.factor; } }console.log(Scale.convert(4),new Scale().factor);Expected output in Node.js:
12 undefinedThe static field and method belong to Scale.
class Config { static n = 2; static { this.n *= 4; } static next = this.n + 1; }console.log(Config.n,Config.next);Expected output in Node.js:
8 9Static field and block evaluation follows textual order.
Common mistakes
Do not expect instance.staticMember to resolve a member stored on the constructor.
Practice
Reorder static fields and blocks in Config and predict the resulting values before running.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Static Class Members and Blocks — Knowledge Check
Apply the taught concept and predict the output.
Where is a public static method installed?
When does a static initialization block run?
Which is a useful static-method purpose?
What is the exact console output in JavaScript Static Class Members and Blocks example 1?
class Scale { static factor = 3; static convert(n) { return n * this.factor; } }console.log(Scale.convert(4),new Scale().factor);What is the exact console output in JavaScript Static Class Members and Blocks example 2?
class Config { static n = 2; static { this.n *= 4; } static next = this.n + 1; }console.log(Config.n,Config.next);