Start learning free

LESSON 627 OF 671 · OBJECT-ORIENTED PROGRAMMING

Static Members in JavaScript: Counting Objects with a Static Field

Practice Read the full explanation

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

    JAVASCRIPT · OBJECT-ORIENTED PROGRAMMING

    Static Members in JavaScript, explained

    Problem overview

    The class Dog already stores a name in each object. The task is to count how many Dog objects have been created, using one counter shared by all of them. The counter must be 0 before any dog exists and must go up by exactly 1 for every dog created, whatever its name.

    The program in the editor creates Rex and Buddy and prints the counter, creates Max, prints the counter and Max's name, then creates Luna without keeping a variable for it and prints the counter once more. Those lines stay as they are. The expected output is:

    2
    3
    Max
    4
    

    Approach: data that belongs to the class

    A normal field such as this.name belongs to one object: every dog has its own. A count of dogs is not a property of any single dog. It describes the class as a whole, so there must be exactly one copy, however many dogs exist.

    A static member does that. Writing static in front of a field attaches it to the class itself, which is itself an object, instead of to each instance. You reach it through the class name, Dog.count. The constructor runs once for every new dog, so it is the natural place to add 1 to the counter.

    Step by step

    1. Declare the static field. Inside the class body, above the constructor, write static count = 0;. The field is created once, when the class is defined, so the counter is 0 before the first new Dog(...).
    2. Count each dog. At the end of the constructor, after this.name = name;, add Dog.count++;. It names the class, not this, because a static field does not exist on the instance.

    The solution in JavaScript

    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);
    

    Running it prints the four lines above. After Rex and Buddy the counter is 2, after Max it is 3, and after Luna it is 4. The last dog was never stored in a variable, and it is counted anyway: the constructor does the counting, not the code that holds the object.

    What to know about static members

    • Instances don't see the static field. With the code above, rex.count is undefined, and Dog.count is a number. The field lives on the class only.
    • Why this.count++ fails quietly. Inside a constructor this is the new object. In a class with static n = 0 and a constructor that runs this.n++, the instance has no n, so the expression computes undefined + 1, which is NaN, and stores it on the new object. The class's n stays 0 and no error appears.
    • Subclasses can read a static field. After class Puppy extends Dog {} and one new Puppy("p"), both Puppy.count and Dog.count read the same shared value. Puppy has no field of its own, so the lookup follows the prototype chain to Dog. The constructor still increments Dog.count, because the code names Dog.
    • Static methods work the same way. static create() { ... } is called as Dog.create(), with no object, and inside it this is the class. A static method can use a static field, but an instance cannot call it directly.
    • The counter is public and writable. Any code can assign Dog.count = 100. Nothing in the lesson guards against that.

    Here is a static method next to the field, in a separate sketch that is not part of the lesson's solution:

    class Dog {
        static count = 0;
        constructor(name) {
            this.name = name;
            Dog.count++;
        }
        static create(name) {
            return new Dog(name);
        }
    }
    
    const d = Dog.create("Fido");
    console.log(d.name, Dog.count); // Fido 1
    console.log(typeof d.create);   // undefined
    

    The method is called on the class and builds a dog through the same constructor, so the counter goes up as usual. The instance d has no create, which is why its typeof is "undefined".

    Edge cases and common mistakes

    • Writing this.count. It reads or writes a separate property on each object and never touches the shared counter.
    • Declaring count as a normal field. A field written without static belongs to each instance. Each dog would get its own counter, starting from 0.
    • Starting at the wrong value. The counter must start at 0. Starting at 1 would print 3, 4 and 5.
    • Incrementing outside the constructor. Adding 1 where the program creates dogs would miss any dog created elsewhere, such as new Dog("Luna") without a variable. The constructor is the one place that every creation passes through.
    • Incrementing before the class has the field. The static field must be declared in the class body. Without it, Dog.count++ would compute undefined + 1 and leave NaN.
    • Changing the printing lines. They are part of the checked program, so only the class changes.

    Key takeaways

    • A static field is one value stored on the class, shared by every instance.
    • Reach it with the class name, Dog.count, never through this or an instance.
    • A constructor runs once per object, so it is the right place to count instances.
    • Static methods use the same keyword and are called on the class.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free