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.GOLDEN_RATIO); // 1.61803
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

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

Practice on your own: Online JavaScript compiler