Static Initialization Blocks
You'll learn how to run complex initialization logic once when a class is defined, using static blocks.
What Are Static Initialization Blocks?
Sometimes you need to perform multi-step setup for your static properties—maybe you need conditional logic, try-catch error handling, or calculations that span multiple lines. A static initialization block runs exactly once when the class is evaluated, giving you a dedicated space for this complex initialization.
Think of it like the "setup phase" that happens before your factory (class) is ready to produce anything. It runs before anyone creates an instance or calls any static methods.
Syntax
Static blocks use the static keyword followed by curly braces:
class Configuration {
static apiKey;
static environment;
static {
// This runs once when the class is evaluated
if (process.env.NODE_ENV === 'production') {
this.apiKey = 'prod-key-12345';
this.environment = 'production';
} else {
this.apiKey = 'dev-key-67890';
this.environment = 'development';
}
}
}
console.log(Configuration.environment); // 'development' or 'production'
When to Use Static Blocks
Use static blocks when:
- You need conditional logic to initialize static properties
- Initialization requires multiple statements
- You want error handling during static setup
- Multiple static properties depend on each other
You can even have multiple static blocks in one class—they execute in order, top to bottom.
Key Takeaway: Static initialization blocks run once when the class is defined, providing a dedicated space for complex static property setup that goes beyond simple assignment.