Start learning free

LESSON 397 OF 410 · OBJECT-ORIENTED PROGRAMMING

Static Members in JavaScript in JavaScript

Practice

TL;DR:

A static field is declared with the static keyword. It belongs to the class itself, so there is one copy shared by every Dog, and you reach it through the class name: Dog.count, never this.count or rex.count. The same keyword also makes static methods (static create() {...}).

You start with:

class Dog {
    constructor(name) {
        this.name = name;
    }
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Add the static field static count = 0; inside Dog.
  • In the constructor, after this.name = name;, add Dog.count++;. A static member is not available as this.count.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count.

class Dog {
    static count = 0;

    constructor(name) {
        this.name = name;
        Dog.count++;
    }
}

let rex = new Dog("Rex");
let buddy = new Dog("Buddy");
console.log(Dog.count);
let third = new Dog("Max");
console.log(Dog.count);
console.log(third.name);
new Dog("Luna");
console.log(Dog.count);

STEP 1 OF 2
    Ctrl + Enter to check

    Static Members in JavaScript

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free