Static Constants

A static constant can be implemented by combining 'static' and 'get'.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

let C = (function(){
   const c1 = 100;
   class C {
      static get myConstant(){return c1;}
   }
   return C;})();C.myConstant = 10;console.log(C.myConstant);  // 100//console.log(c1);  // ReferenceError

</script></body><html>

ECMAScript 2022 made this workaround largely unnecessary by allowing static fields (public and, with the # prefix, private) to be declared directly in the class body, alongside the static methods that have existed since ES6.


class C {
  static myConstant = 100;   // static public field
  static #secret = 42;       // static private field
  static reveal() { return C.#secret; }
}

console.log(C.myConstant);
C.myConstant = 10;   // public: freely reassignable, unlike the getter-only version
console.log(C.myConstant);
console.log(C.reveal());

// console.log(C.#secret);   // SyntaxError outside the class body

100 10 42

A static initialization block — a static{...} block inside the class body — runs once, when the class itself is being defined, with access to private fields. It is useful for computing static state that a single field initializer cannot express, such as state that depends on a try...catch or on another private static member.


class Config {
  static #env;
  static settings;

  static {
    try {
      Config.#env = detectEnvironment();
    } catch {
      Config.#env = 'unknown';
    }
    Config.settings = {env: Config.#env, ready: true};
  }
}

function detectEnvironment() { return 'production'; }

console.log(Config.settings);

{env: 'production', ready: true}