Normally, methods belong to instances: you call user.greet(). A static member belongs to the class itself: you call User.something(), and instances do not have it.
class MathUtil {
static square(n) {
return n * n;
}
static PI = 3.14159;
}
console.log(MathUtil.square(5)); // → 25
console.log(MathUtil.PI); // → 3.14159
There is no need to create an instance. static is for things related to the class as a whole.
Factory methods
A static method that creates instances in a convenient way:
class User {
constructor(name, role) {
this.name = name;
this.role = role;
}
static admin(name) {
return new User(name, "admin");
}
static fromJSON(text) {
const { name, role } = JSON.parse(text);
return new User(name, role);
}
}
console.log(User.admin("Maya").role); // → admin
console.log(User.fromJSON('{"name":"Sam","role":"editor"}').name); // → Sam
Shared counters and settings
class Widget {
static count = 0;
constructor() {
Widget.count++;
}
}
new Widget();
new Widget();
console.log(Widget.count); // → 2
Static vs instance
class Example {
static hello() { return "static"; }
hello() { return "instance"; }
}
console.log(Example.hello()); // → static
console.log(new Example().hello()); // → instance
An instance cannot call a static method directly (new Example().staticMethod is undefined). Inside a static method, this is the class.
Static blocks
A static initialization block runs once when the class is defined, for more complex setup.
class Config {
static defaults;
static {
Config.defaults = { theme: "light", fontSize: 16 };
}
}
console.log(Config.defaults.theme); // → light
Inheritance
Static members are inherited by subclasses.
class Animal {
static kingdom = "Animalia";
}
class Dog extends Animal {}
console.log(Dog.kingdom); // → Animalia
Static private
static #cache = new Map(); and static #helper() {} also exist.
When to use static
- Utility functions related to the class (
Date.now(),Array.isArray(),Object.keys()are static methods you already use). - Factory methods and constructors with different inputs.
- Class-level constants and counters.
If a static method does not relate to the class at all, a plain function in a module is clearer.