Methods on the Class, Not the Instance
JavaScript Static Members
`static` methods and fields belong to the class itself, not to instances. Great for factories, constants, and utilities.
What you'll learn
- Declare static methods and fields
- Know when to use static vs instance methods
Class members marked static belong to the class itself — not to any
instance. You call them via the class name.
class MathUtil {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(MathUtil.add(2, 3)); // 5
console.log(MathUtil.multiply(4, 5)); // 20
// const m = new MathUtil();
// m.add(2, 3); // TypeError — add is not on the instance Static methods don’t have access to instance this (there’s no
instance involved). They’re plain functions namespaced under a class.
Static Fields
You can attach data to the class too — useful for constants or configuration.
class HttpClient {
static defaultTimeout = 5000;
static maxRetries = 3;
}
console.log(HttpClient.defaultTimeout); // 5000
HttpClient.defaultTimeout = 10000; // mutable unless you Object.freeze
console.log(HttpClient.defaultTimeout); // 10000 A Classic Use: Factory Methods
A static method that returns a new instance is called a factory method. Useful when there are multiple ways to construct an object.
class User {
constructor(name, role) {
this.name = name;
this.role = role;
}
static makeAdmin(name) {
return new User(name, "admin");
}
static makeGuest() {
return new User("Guest", "guest");
}
}
const ada = User.makeAdmin("Ada");
const g = User.makeGuest();
console.log(ada); // User { name: 'Ada', role: 'admin' }
console.log(g); // User { name: 'Guest', role: 'guest' } Static Methods on Built-ins
You’ve used static methods on built-in classes all along:
- “
Math.max(...),Math.random()— static onMath.” Object.keys(obj),Object.entries(obj)— static onObject.Array.isArray(x),Array.from(x)— static onArray.Number.isFinite(x)— static onNumber.
These all illustrate the pattern — class-level utilities that don’t need an instance.
When to Use Static
- Factory methods (
User.makeGuest()). - Utility functions that don’t depend on instance state.
- Class-level constants and configuration.
- Type guards / branding helpers (like the private-field
incheck).
Don’t put everything static — if a method operates on instance state, it should be an instance method.
Up Next
Properties that look like data but actually run a function — getters and setters.
JavaScript Getters & Setters →