JavaScript static {}

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

A static { } block runs once when the class is evaluated—useful for multi-step static setup that is awkward as field initializers.

JavaScript Syntax

JavaScript
class Config {
  static values = {};
  static {
    this.values.mode = "dev";
  }
}
console.log(Config.values.mode);
Try it Editor

How It Works

  1. Class loads. static block runs.
  2. this is the class. Sets values.mode.

Examples

Example 1 — Runs at definition

Before you construct instances.

JavaScript
let n = 0; class A { static { n = 1; } }
console.log(n);
Try it Editor

How It Works

  1. Block ran when class evaluated.

Example 2 — Multiple blocks

Allowed; run in order.

JavaScript
class A { static a = 0; static { this.a = 1; } static { this.a = 2; } }
console.log(A.a);
Try it Editor

How It Works

  1. Later block wins.

Example 3 — Access private statics

Blocks can touch #statics.

JavaScript
class A { static #x; static { this.#x = 5; } static getX(){ return this.#x; } }
console.log(A.getX());
Try it Editor

How It Works

  1. Private static initialized in block.

Frequently Asked Questions

When static setup needs statements (try/catch, loops), not just a single expression.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful