Skip to main content

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 function

Reason: 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)); // 8

Here 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"

extends inherits 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 // Dog

6. 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 CalledExampleDoes It Work?
On the classUser.sayHi()Yes
On an instancenew User().sayHi()No
Inside another staticthis.otherStatic()Yes
Inside a regular methodClassName.staticMethod()Yes
In a subclass via supersuper.staticMethod()Yes

In short:

Static methods are called on the class itself, not on its instances:

javascript
ClassName.methodName();

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.