In JavaScript, classes allow you to create objects with shared structure and behavior. Among the many features of classes, static properties hold a unique place. Unlike instance properties, which belong to each individual object created from a class, static properties belong to the class itself. This means static properties are shared across all instances and accessed directly from the class, not from the objects created by it.
Static properties are particularly useful when you want to keep track of data or state that applies to the entire class rather than to each object separately. Imagine a basketball team class that keeps track of how many teams have been created in total — a static property can hold this count. This article will guide you step-by-step on how to define, access, and manipulate static properties in JavaScript classes, with lively examples that make the concepts clear and enjoyable.
Defining Static Properties in JavaScript Classes
To declare a static property in a JavaScript class, you use the static
keyword before the property name inside the class body. This tells JavaScript that this property belongs to the class itself, not to instances.
Consider this example of a simple Game
class that keeps track of how many games have been created. The static property count
starts at zero and increases every time a new game instance is created:
class Game {
static count = 0;
constructor(name) {
this.name = name;
Game.count++;
}
}
console.log(Game.count); // 0 before any instances
const game1 = new Game("Chess");
const game2 = new Game("Checkers");
console.log(Game.count); // 2 after two instances
In this code, the static property count
belongs to the Game
class. Each time the constructor runs, it increments the count, tracking the total number of game instances created. Notice that we access count
directly on Game
, not on game1
or game2
.
Accessing Static Properties
Static properties are accessed directly on the class, not on instances. Attempting to access a static property from an instance will result in undefined
or an error, depending on the context.
Let’s see how this works with a Wizard
class. We’ll have a static property school
representing the magical school’s name, accessible only on the class itself:
class Wizard {
static school = "Hogwarts";
constructor(name) {
this.name = name;
}
}
console.log(Wizard.school); // "Hogwarts"
const harry = new Wizard("Harry Potter");
console.log(harry.school); // undefined — static property not on instance
The school
property belongs to Wizard
as a whole. Accessing it from harry
, an instance, does not work because school
is not part of the instance’s own properties.
Modifying Static Properties
Static properties can be modified directly on the class. Since the property is shared, any change affects the class and all code that relies on that property.
Imagine a BasketballTeam
class that tracks the total wins across all teams using a static property totalWins
:
class BasketballTeam {
static totalWins = 0;
constructor(name) {
this.name = name;
}
addWin() {
BasketballTeam.totalWins++;
}
}
const team1 = new BasketballTeam("Lions");
const team2 = new BasketballTeam("Elephants");
team1.addWin();
team2.addWin();
team2.addWin();
console.log(BasketballTeam.totalWins); // 3
Here, both team instances can increment the shared static property totalWins
. The static property is updated on the class level, so it accurately tracks wins from all teams combined.
Using Static Properties in Static Methods
Static methods often work alongside static properties to manipulate or retrieve shared class data. A static method is defined with the static
keyword and called directly on the class.
Consider a ChessPlayer
class that tracks how many players have been created, using both a static property and a static method:
class ChessPlayer {
static totalPlayers = 0;
constructor(name) {
this.name = name;
ChessPlayer.incrementPlayers();
}
static incrementPlayers() {
ChessPlayer.totalPlayers++;
}
static getTotalPlayers() {
return ChessPlayer.totalPlayers;
}
}
new ChessPlayer("Magnus");
new ChessPlayer("Hikaru");
console.log(ChessPlayer.getTotalPlayers()); // 2
The static method incrementPlayers
updates the static property totalPlayers
. The method getTotalPlayers
returns the current count. This encapsulation keeps the logic organized and easy to manage.
Static Properties Outside the Class Definition
JavaScript also allows static properties to be added to a class after it’s defined. This can be useful when you want to assign or update static properties dynamically.
Here is a Cat
class example where we assign a static property outside the class:
class Cat {
constructor(name) {
this.name = name;
}
}
Cat.totalCats = 0;
const whiskers = new Cat("Whiskers");
const mittens = new Cat("Mittens");
Cat.totalCats = 2;
console.log(Cat.totalCats); // 2
While this method works, defining static properties inside the class is generally cleaner and more common. But the flexibility to add or change static properties later exists when needed.
Fun Real-World Example Combining All Concepts
To bring everything together, let’s create a Movie
class that uses static properties and methods to keep track of the total number of movies and their combined box office earnings.
class Movie {
static totalMovies = 0;
static totalBoxOffice = 0;
constructor(title, boxOffice) {
this.title = title;
this.boxOffice = boxOffice;
Movie.totalMovies++;
Movie.totalBoxOffice += boxOffice;
}
static getAverageBoxOffice() {
return (Movie.totalBoxOffice / Movie.totalMovies).toFixed(2);
}
}
const movie1 = new Movie("Lion King", 1650000000);
const movie2 = new Movie("Madagascar", 532000000);
const movie3 = new Movie("Black Panther", 1340000000);
console.log(`Total movies: ${Movie.totalMovies}`); // 3
console.log(`Total box office: $${Movie.totalBoxOffice}`); // 3522000000
console.log(`Average box office: $${Movie.getAverageBoxOffice()}`); // 1174000000.00
Each time a new Movie
instance is created, the static properties totalMovies
and totalBoxOffice
update accordingly. The static method getAverageBoxOffice
calculates the average box office earnings of all movies combined. This example illustrates how static properties hold shared data and static methods provide useful operations on that data.
Conclusion
Static properties in JavaScript classes are powerful tools for holding shared data at the class level. They differ from instance properties by being accessible only on the class, not individual objects. You can define static properties inside a class with the static
keyword or assign them later outside the class body. Modifying static properties affects the class itself and all instances that rely on it.
By combining static properties with static methods, you can create well-structured and clear code that tracks shared state and provides useful class-level functionality. The examples from games, wizards, sports teams, and movies show how you can make your JavaScript classes more dynamic and engaging with static properties.
References
If you want to learn more about JavaScript static properties and related class features, these resources are excellent starting points:
- MDN Web Docs: Classes – Static
The official documentation explaining static properties and methods in JavaScript classes. - MDN Web Docs: Static Methods
Understand how static methods work and how they relate to static properties.