๐Ÿ“˜ JavaScript Class Static

โœ… What Are Static Methods and Properties?

  • Static methods and properties belong to the class itself, not to instances of the class.
  • You call static methods directly on the class, not on objects created from it.
  • Useful for utility functions, constants, or helper methods related to the class but not tied to any specific object.

๐Ÿ“Œ Basic Syntax for Static Methods

jsCopyEditclass MathHelper {
  static square(x) {
    return x * x;
  }
}

console.log(MathHelper.square(5)); // 25

const mh = new MathHelper();
// mh.square(5); // โŒ Error: square is not a function on instances
  • static keyword defines the static method.
  • Trying to call the method on an instance causes an error.

๐Ÿ“Œ Static Properties (ES2022+)

You can also define static properties directly in the class:

jsCopyEditclass Circle {
  static pi = 3.14159;

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

  area() {
    return Circle.pi * this.radius ** 2;
  }
}

console.log(Circle.pi); // 3.14159

const c = new Circle(5);
console.log(c.area()); // 78.53975

๐Ÿ“Œ Use Cases for Static Members

  • Constants: Like Math.PI or configuration values.
  • Utility functions: Helper methods related to the class but donโ€™t require instance data.
  • Factory methods: Create instances with preset options.

Example of a factory static method:

jsCopyEditclass User {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }

  static guestUser() {
    return new User("Guest", "guest");
  }
}

const guest = User.guestUser();
console.log(guest.name); // Guest

๐Ÿ“Œ Accessing Static Members from Instance Methods

Inside instance methods, to access static members, use the class name:

jsCopyEditclass Counter {
  static count = 0;

  constructor() {
    Counter.count++;
  }

  getCount() {
    return Counter.count;
  }
}

const a = new Counter();
const b = new Counter();

console.log(a.getCount()); // 2
console.log(Counter.count); // 2

Summary Table

FeatureUsageCalled On
Static Methodstatic methodName() {}Class itself
Static Propertystatic propName = value;Class itself
Instance MethodmethodName() {}Instances
Access Static in InstanceUse ClassName.staticMemberFrom instance methods

Practice Challenge

  1. Create a class Temperature with a static method celsiusToFahrenheit(c) converting Celsius to Fahrenheit.
  2. Add a static property freezingPoint set to 0.
  3. Use these static members without creating an instance.