How do you call a static method?
1. Syntax for Calling a Static Method
javascript
class User {
static sayHi() {
console.log("Hi from the User class!");
}
}
// Correct:
User.sayHi(); // Hi from the User class!
// Incorrect:
const u = new User();
u.sayHi(); // TypeError: u.sayHi is not a functionReason: static methods belong to the class itself,
not to objects created with new.
2. Example With Parameters
javascript
class MathUtils {
static sum(a, b) {
return a + b;
}
}
console.log(MathUtils.sum(3, 5)); // 8Here
MathUtils.sum()is called directly through the class name.
3. Static Methods With Inheritance
If a class inherits from another (extends),
it also gets access to the parent's static methods:
javascript
class Animal {
static info() {
console.log("This is an animal");
}
}
class Dog extends Animal {}
Dog.info(); // "This is an animal"
extendsinherits both regular and static methods.
4. Calling a Static Method Inside the Class
You can call static methods:
- either through the class name (
User.someMethod()), - or through
this(inside other static methods), - but not from an instance.
javascript
class User {
static hello() {
console.log("Hi!");
}
static greetAll() {
this.hello(); // works: `this` = the class itself
}
sayHi() {
// Can't call a static method directly from here
// this.hello(); // TypeError
User.hello(); // works through the class name
}
}
const u = new User();
User.greetAll(); // Hi!
u.sayHi(); // Hi!5. Calling the Parent's Static Method via super
If you have inheritance, you can call the parent's static method using super:
javascript
class Animal {
static describe() {
console.log("Animal");
}
}
class Dog extends Animal {
static describe() {
super.describe(); // calls Animal.describe()
console.log("Dog");
}
}
Dog.describe();
// Animal
// Dog6. A Real-Life Example: A Factory Method
javascript
class User {
constructor(name, role) {
this.name = name;
this.role = role;
}
static createGuest() {
return new User("Guest", "guest");
}
}
const guest = User.createGuest(); // calling the static method
console.log(guest); // { name: "Guest", role: "guest" }Here User.createGuest() returns a new instance,
but the method itself belongs to the class, not to an object.
Summary
| Where It's Called | Example | Does It Work? |
|---|---|---|
| On the class | User.sayHi() | Yes |
| On an instance | new User().sayHi() | No |
Inside another static | this.otherStatic() | Yes |
| Inside a regular method | ClassName.staticMethod() | Yes |
In a subclass via super | super.staticMethod() | Yes |
In short:
Static methods are called on the class itself, not on its instances:
javascriptClassName.methodName();
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.