Course contentsShow
← JavaScript
Lesson 786 of 2,72318. ClassesFree lesson

Declaring Static Properties

Use the 'static' keyword before property declarations inside the class body to define static properties.

Declaring Static Properties

In this lesson, you'll learn how to define properties that belong to the class itself, not to instances.

What Are Static Properties?

Just like static methods belong to the class rather than to individual instances, static properties are variables stored on the class itself. They're shared across all instances and accessed directly through the class name.

Using the static Keyword for Properties

To declare a static property, use the static keyword before the property declaration inside the class body:

class Counter {
  static totalCount = 0;  // Static property
  
  constructor(name) {
    this.name = name;
    Counter.totalCount++;  // Access via class name
  }
}

console.log(Counter.totalCount);  // 0

const counter1 = new Counter('First');
const counter2 = new Counter('Second');

console.log(Counter.totalCount);  // 2
console.log(counter1.totalCount); // undefined (not on instances!)

Why This Matters

Static properties are perfect for storing data that should be shared across all instances of a class—like configuration values, counters, or cached data. They exist once in memory, attached to the class itself.

Think of it like a school's principal's office: there's only one principal's office for the entire school (static property), even though there are many individual classrooms (instances).

class Config {
  static apiUrl = 'https://api.example.com';
  static maxRetries = 3;
}

console.log(Config.apiUrl);     // 'https://api.example.com'
console.log(Config.maxRetries); // 3

Key Takeaway: Use the static keyword before property declarations inside the class body to create properties that belong to the class itself and are shared across all instances.