Skip to main content

Static Methods in JavaScript Classes (Live Playground)

Static methods in JavaScript classes are methods that can be called on the class itself, without instantiating an object of the class. In this tutorial, we'll explore the syntax and usage of static methods in JavaScript classes.

Static Methods Syntax

To define a static method, use the static keyword followed by the method name within the class body:

class Circle {
constructor(radius) {
this.radius = radius;
}

// Static method to calculate the area of a circle
static calculateArea(radius) {
return Math.PI * Math.pow(radius, 2);
}
}

In this example, we've defined a static method calculateArea that calculates the area of a circle given its radius.

Using Static Methods

Static methods can be called directly on the class, without creating an instance of the class:

const area = Circle.calculateArea(5);
console.log(area); // 78.53981633974483

In this example, we've called the calculateArea static method directly on the Circle class without creating a Circle object.

Live Playground, Try it Yourself

Conclusion

In this tutorial, we learned about static methods in JavaScript classes, their syntax, and usage. Static methods are useful when you need to perform operations related to a class that do not depend on the state of a particular instance. They can be called directly on the class, without creating an instance of the class, making your code more efficient in certain cases.