Lesson 23 - JavaScript Static Methods and Properties
What is a static method?
Static methods and properties belong to the class itself rather than instances of the class. They are useful for utility functions, constants, and helper methods that do not require an instance.
Example 1: Static Methods
class MathHelper {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(MathHelper.add(5, 3)); // Output: 8
console.log(MathHelper.subtract(10, 4)); // Output: 6
? We call add() and subtract() directly on the class!
Explanation
statickeyword is used to define static methods and properties.- They are accessed using the class name instead of an instance.
- Static methods cannot access
thisinside instance methods.
Example 2: Static Properties
class Config {
static appName = "MyApp";
static version = "1.0.0";
static getInfo() {
return `${this.appName} - Version ${this.version}`;
}
}
console.log(Config.appName); // Output: MyApp
console.log(Config.getInfo()); // Output: MyApp - Version 1.0.0
- We access
appNameandgetInfo()directly from the class!
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson23-static.html.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 23 - Static Methods</title> </head> <body> <script> class Temperature { static toCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; } static toFahrenheit(celsius) { return (celsius * 9 / 5) + 32; } } console.log(Temperature.toCelsius(100)); // Converts 100°F to Celsius console.log(Temperature.toFahrenheit(0)); // Converts 0°C to Fahrenheit </script> </body> </html>
-
-
Save the File.
-
Preview in Browser and Check Console Output.
Experiment
-
Modify
MathHelperto include amultiply()method:class MathHelper { static multiply(a, b) { return a * b; } } console.log(MathHelper.multiply(4, 5)); // Output: 20 - Add a new static property to
Confignamedauthorand access it.
Key Takeaways
- Use
staticfor methods and properties that belong to the class. - They cannot be called on class instances.
- Static methods are great for utility functions.