- Home
- /
- JS Static Method
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS Static Method
Static Methods in JavaScript
In object-oriented programming, a static method is a method that belongs to a class itself, not to instances of the class. This means you can call the method without creating an object of the class.
Defining a Static Method
In JavaScript, static methods are created using the static
keyword inside a class.
class MathHelper {
static add(a, b) {
return a + b;
}
}
console.log(MathHelper.add(1, 2)); // Output: 3
You don’t need to use new MathHelper()
to call add()
. It’s accessed directly from the class.
When to Use Static Methods
Static methods are useful for:
Utility or helper functions (like mathematical operations)
Creating factory methods
Performing actions that don’t rely on instance data
class IDGenerator {
static generate() {
return Math.floor(Math.random() * 10000);
}
}
console.log(IDGenerator.generate());
Notes
Static methods do not access
this
becausethis
refers to an instance, and static methods don’t operate on instances.Static methods can access other static methods or static properties in the same class.
Summary
Use
static
to define class-level methods.Call static methods using the class name (not instance).
Best for utility-like functions or actions that don’t depend on instance data.
Static methods cannot access instance properties or
this
.