Table of Contents
Static class methods are defined with the static keyword.
Static methods are called directly on the class (without creating an instance of the class).
Static methods are often used for utility functions that are not specific to a particular object:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Static</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Static Class Methods</h4>
<p id="demo"></p>
<script>
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!";
}
}
document.getElementById("demo").innerHTML = Car.hello();
</script>
</body>
</html>

Result View Example
Static methods are called on the class itself, not on instances of the class:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Static</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Calling Static Methods</h4>
<p id="demo"></p>
<script>
class Calculator {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
// Call static methods on the class directly
let sum = Calculator.add(5, 3);
let product = Calculator.multiply(5, 3);
document.getElementById("demo").innerHTML =
"5 + 3 = " + sum + "<br>" +
"5 * 3 = " + product;
</script>
</body>
</html>

Result View Example
Static methods are defined on the class level. Instance methods are defined on the prototype and are available on object instances:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Static</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Static vs Instance Methods</h4>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
class Car {
constructor(name) {
this.name = name;
}
// Instance method
start() {
return this.name + " engine started!";
}
// Static method
static description() {
return "A car is a wheeled motor vehicle used for transportation.";
}
}
const myCar = new Car("Ford");
// Call instance method on the object
document.getElementById("demo1").innerHTML = myCar.start();
// Call static method on the class
document.getElementById("demo2").innerHTML = Car.description();
// Trying to call static method on an instance would cause an error
try {
myCar.description();
} catch(err) {
document.getElementById("demo3").innerHTML = "Error: " + err.message;
}
</script>
</body>
</html>

Result View Example
Document in project
You can Download PDF file.