Static Methods and Properties

Sophomore Year, page 4 of 11. A one-minute read.

Normally, methods belong to instances: each cookie can do things. But sometimes a function is related to the class as a whole, rather than any one instance. For that, use static:

JavaScript
class Temperature {
  static FREEZING = 0;

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

  get fahrenheit() {
    return (this.celsius * 9) / 5 + 32;
  }

  static fromFahrenheit(f) {
    return new Temperature(((f - 32) * 5) / 9);
  }

  isFreezing() {
    return this.celsius <= Temperature.FREEZING;
  }
}

const hot = new Temperature(35);
console.log(hot.fahrenheit);

const fromUS = Temperature.fromFahrenheit(212);
console.log(fromUS.celsius);
console.log(Temperature.FREEZING);
console.log(new Temperature(-3).isFreezing());

It prints

95
100
0
true

You call static methods and read static properties on the class itself (Temperature.fromFahrenheit), not on an instance. You've used static methods before without knowing it: Number.isNaN(), Array.from(), Object.keys() and Promise.all() are all static methods!

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning