Class Static Initialization Blocks
You'll learn how to run complex static initialization logic exactly once when a class is first evaluated.
What Is a Static Initialization Block?
A static initialization block is a special static {} block inside a class that runs automatically when the class itself is loaded—not when you create instances. It's perfect for setup logic that's too complex for a simple static property assignment.
Think of it like a "boot-up sequence" for your class: Before anyone can use the class (even before creating the first instance), this code runs once to prepare everything.
The Syntax
class DatabaseConnection {
static #connectionPool = [];
static maxConnections;
static {
// This runs once when the class is evaluated
console.log("Initializing connection pool...");
this.maxConnections = this.#validateEnvironment();
this.#connectionPool = this.#createInitialPool();
}
static #validateEnvironment() {
// Complex validation logic
return 10;
}
static #createInitialPool() {
return Array(this.maxConnections).fill(null);
}
}
// "Initializing connection pool..." logs immediately
Why Use It?
You need static initialization blocks when:
- Setting up a static property requires multiple steps
- You need to call private static methods during initialization
- Your static setup involves conditions, loops, or error handling
- You want to keep initialization logic grouped together
The block runs in the class scope, so this refers to the class itself, and you can access private static fields and methods.
Key Takeaway: Use static {} blocks to execute complex one-time initialization logic when your class is first loaded, with full access to private static members.