In JavaScript, Static Properties are variables defined directly on a class rather than on instances of that class. They are shared across all instances but are accessed via the class itself. Think of them as “class-level variables” used for constants, configuration settings, or data that should be global to the class.

1. Syntax and Basic Usage

You define a static property using the static keyword. Like static methods, they are not accessible through a new instance of the class.

JavaScript

class Configuration {
  static API_URL = "https://api.example.com";
  static TIMEOUT = 5000;
}

// ✅ Access via the class
console.log(Configuration.API_URL); // "https://api.example.com"

// ❌ Cannot access via an instance
const config = new Configuration();
console.log(config.API_URL); // undefined

2. Shared State Between Instances

Because static properties live on the class, every instance “sees” the same value. This makes them perfect for tracking metadata across all objects created from that class, such as a counter.

JavaScript

class User {
  static count = 0; // Shared counter

  constructor(name) {
    this.name = name;
    User.count++; // Increment the class-level property
  }
}

const u1 = new User("Alice");
const u2 = new User("Bob");

console.log(User.count); // 2

3. Static Private Properties

With modern JavaScript (ES2022+), you can combine the static keyword with the # prefix to create Static Private Properties. These are variables that belong to the class but cannot be accessed or modified from outside the class body.

JavaScript

class SecureConnection {
  static #apiKey = "SECRET_12345"; // Private and static

  static getInfo() {
    // Accessible inside the class
    return `Connection active with key: ${this.#apiKey}`;
  }
}

console.log(SecureConnection.getInfo()); // Works
// console.log(SecureConnection.#apiKey); // SyntaxError: Private field must be declared

4. Inheritance of Static Properties

Static properties are inherited by subclasses. When a child class extends a parent, it gains access to the parent’s static properties via the prototype chain of the constructors.

JavaScript

class Settings {
  static theme = "dark";
}

class DashboardSettings extends Settings {}

console.log(DashboardSettings.theme); // "dark"

5. Real-World Use Case: Global Constants

In many applications, you’ll see static properties used to avoid “magic strings” or hardcoded numbers, keeping the logic centralized within a relevant class.

JavaScript

class FileSystem {
  static MAX_FILE_SIZE_MB = 25;
  static ALLOWED_EXTENSIONS = ['.jpg', '.png', '.pdf'];

  upload(file) {
    if (file.size > FileSystem.MAX_FILE_SIZE_MB * 1024 * 1024) {
      console.error("File too large!");
    }
  }
}

Categorized in:

Javascript,