How to Use Static Method in JavaScript: Simple Guide
In JavaScript, a
static method is defined inside a class using the static keyword and can be called directly on the class without creating an instance. You use it by calling ClassName.methodName(), not on an object instance.Syntax
A static method is declared inside a class using the static keyword before the method name. It belongs to the class itself, not to any object created from the class.
- static: keyword to define a static method
- methodName(): the name of the static method
- Called using
ClassName.methodName(), not on instances
javascript
class MyClass { static myStaticMethod() { return 'Hello from static method!'; } }
Example
This example shows how to define a static method and call it directly on the class. It also shows that instances of the class cannot call the static method.
javascript
class Calculator { static add(a, b) { return a + b; } } // Call static method on the class console.log(Calculator.add(5, 7)); // Create an instance const calc = new Calculator(); // Trying to call static method on instance will cause error // console.log(calc.add(5, 7)); // Uncaught TypeError
Output
12
Common Pitfalls
One common mistake is trying to call a static method on an instance of the class instead of the class itself. Static methods are not available on instances.
Another mistake is forgetting to use the static keyword, which makes the method an instance method instead.
javascript
class Person { // Wrong: missing static keyword greet() { return 'Hello!'; } } const p = new Person(); console.log(p.greet()); // Works because greet is instance method // Correct way with static class PersonStatic { static greet() { return 'Hello!'; } } console.log(PersonStatic.greet()); // Works // console.log(new PersonStatic().greet()); // Error: greet is not a function
Output
Hello!
Hello!
Quick Reference
Remember these key points about static methods:
- Use
statickeyword inside class to define them. - Call them on the class itself, not on instances.
- Useful for utility functions related to the class but not to individual objects.
Key Takeaways
Static methods belong to the class, not to instances.
Use the static keyword to define a static method inside a class.
Call static methods using ClassName.methodName(), not instance.methodName().
Trying to call static methods on instances causes errors.
Static methods are great for utility functions related to the class.