Declaring Static Methods
In this lesson, you'll learn how to use the static keyword to create methods that belong to the class itself, not its instances.
What Makes a Method Static?
You already know that static methods belong to the class itself rather than to individual objects created from that class. Now let's see how to actually create them.
Using the static Keyword
To declare a static method, simply place the static keyword before the method name inside your class body:
class MathHelper {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
// Call directly on the class
console.log(MathHelper.add(5, 3)); // 8
console.log(MathHelper.multiply(4, 2)); // 8
The static keyword tells JavaScript: "This method belongs to the class constructor itself, not to instances."
Mixing Static and Instance Methods
You can have both static and regular (instance) methods in the same class:
class User {
constructor(name) {
this.name = name;
}
// Instance method
greet() {
return `Hello, I'm ${this.name}`;
}
// Static method
static createGuest() {
return new User('Guest');
}
}
const guest = User.createGuest(); // Called on class
console.log(guest.greet()); // Called on instance
Notice how createGuest() is called on the User class itself, while greet() is called on an instance.
Key Takeaway: Use the static keyword before a method name in a class body to create a static method that belongs to the class rather than its instances.