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); // 2Static 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.14159Challenge
Add static properties PI and E to a MathConstants class:
- Static property
PIset to3.14159 - Static property
Eset to2.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); // 2Static properties are useful for class-level constants:
class MathConstants {
static PI = 3.14159;
static E = 2.71828;
}
console.log(MathConstants.PI); // 3.14159Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge