Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

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

  • static keyword is used to define static methods and properties.
  • They are accessed using the class name instead of an instance.
  • Static methods cannot access this inside 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 appName and getInfo() directly from the class!

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson23-static.html.
  2. 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>
  3. Save the File.

  4. Preview in Browser and Check Console Output.


Experiment

  1. Modify MathHelper to include a multiply() method:

    class MathHelper {
       static multiply(a, b) {
           return a * b;
       }
    }
    
    console.log(MathHelper.multiply(4, 5)); // Output: 20
  2. Add a new static property to Config named author and access it.

Key Takeaways

  • Use static for methods and properties that belong to the class.
  • They cannot be called on class instances.
  • Static methods are great for utility functions.