Static Fields and Methods

It is possible to create static fields and methods in JavaScript classes.

class Math {
  static PI = 3.14;

  static max(...args) { 
    let max = Number.MIN_SAFE_INTEGER;
    args.forEach( arg => max = max < arg ? arg : max );
    return max;
  }
}

console.log(Math.PI);
console.log(Math.max(3, 0, 5));

Static fields/method in JavaScript, like in Java/C++, are class members and not instance members. So, you access/invoke them using the class name (not the instantiated object).

A class is technically a function! A function is technically an object, so a class is an object!! You can add value/function properties outside of class definition. Those will be added as static members.

class Person {
  constructor(name) {
    this.name = name;
  }
}

Person.genus = "homosapien";

const person = new Person("Ali");

console.log(person);
console.log(Person.genus)