Menu
Coddy logo textTech

Static Properties

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 32 of 56.

Static properties belong to the class itself, not to instances of the class. They are shared among all instances.

Define a class with a static property:

class Counter {
  // Define a static property
  static count = 0;
  
  constructor() {
    // Increment the static count each time a new instance is created
    Counter.count++;
  }
}

Access the static property using the class name:

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

// Create some instances
const counter1 = new Counter();
const counter2 = new Counter();

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

Static properties are useful for values that should be shared across all instances or for class-level constants. For example:

class MathConstants {
  static GOLDEN_RATIO = 1.61803;
}

console.log(MathConstants.PI); // 3.14159
challenge icon

Challenge

Add static properties PI and E to a MathConstants class:

  1. Static property PI set to 3.14159
  2. Static property E set to 2.71828

Cheat sheet

Static properties belong to the class itself, not to instances. They are shared among all instances and accessed using the class name.

Define a static property using the static keyword:

class Counter {
  static count = 0;
  
  constructor() {
    Counter.count++;
  }
}

Access static properties through the class name:

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

const counter1 = new Counter();
const counter2 = new Counter();

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

Static properties are useful for class-level constants:

class MathConstants {
  static PI = 3.14159;
  static E = 2.71828;
}

console.log(MathConstants.PI); // 3.14159

Try it yourself

import { MathConstants } from './constants.js';

// Test code - don't modify
console.log(MathConstants.PI);        // Should output 3.14159
console.log(MathConstants.E);         // Should output 2.71828
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming