JS: Class static block

By Xah Lee. Date: . Last updated: .

What is class static block

(new in ECMAScript 2022)

A Class Static Block is a syntax that lets the class run a block of code when a class definition is evaluated.

class Xclass {
 static {
  console.log("i ran!");
 }
}
// i ran!

Purpose

The purpose of static block is to make initialization of the class easier, have access to private fields and methods. Otherwise, you have to write a static method and call it, but that does not have access to static private fields, it also pollutes the property key space of the constructor.

Syntax

static {code}

Multiple static blocks

class Xclass {

// multiple class static blocks

 static {
  console.log("i ran first.");
 }

 static {
  console.log("i ran second.");
 }
}
// i ran first.
// i ran second.

Local variable and functions

class Xclass {
 static {
  // class static block can have local variables and local functions
  let x = 3;

  function good_morn() {
   return `good morning, i have ${x} cats.`;
  }

  console.log(good_morn());
 }
}
// good morning. i have 3 cats.

This-binding

class Xclass {
 static {
  // inside static block, value of this-binding is the class constructor
  console.assert(this === Xclass);
 }
}

Access to static private elements

class Xclass {
 // private field
 static #cat = 3;
 static {
  console.log(Xclass.#cat);
 }
}
// 3

Execution order of static elements

Static elements are run in order, from top down. For example, it is an error if you access a static private field that appears below.

However static methods are available regardless of order.

🟢 tip: best to arrange all your static elements in order. with static fields appear first or static private fields, followed by static methods, followed by static blocks.

// Static elements are run in order, from top down. it is an error if you access a static private field that appears below.
class Xclass {
 static {
  console.log(Xclass.#dog);
 }
 static #dog = 4;
}
// error: Uncaught (in promise) TypeError: Cannot read private member #dog from an object whose class did not declare it
// static methods are available in static block code, regardless of the source code order of the static method

class Xclass {
 static {
  console.log(Xclass.add1(1));
 }
 static add1(x) {
  return x + 1;
 }
}
// 2

Return, Await, yield, not allowed

Super class's static block are run

// in class static block, the super class's static block are run first

class AA {
 static {
  console.log("i am super.");
 }
}

class BB extends AA {}
// i am super.

Access super class's static elements

in class static block, you can access super class's static field by

super.field_name

note: you cannot call super(), because that is not for static initialization.

// in class static block, you can access super class's static field by super.field_name

class AA {
 static cat = 3;
}

class BB extends AA {
 static {
  console.log(super.cat);
 }
}
// 3