All sample questions / JavaScript

JavaScript this, Prototypes and Classes, what does console.log(Shape.count) print after class Shape?

Block 3, this, Prototypes and Classes, question 18 of the JavaScript sample

class Shape {
  static count = 0;
  constructor() {
    Shape.count++;
  }
}
class Circle extends Shape {}
new Circle();
new Circle();
new Shape();
console.log(Shape.count);

What does this print?

  1. A. 2
  2. B. 3
  3. C. 1
  4. D. 0
Show the answer and why each option is right or wrong

Answer, B. 3

A. 2
Assumes creating a Circle instance does not touch the static counter defined on Shape, only direct Shape instances would. Circle has no constructor of its own, so it implicitly calls the inherited Shape constructor, which still runs the increment.
B. 3
Correct. Every instance, whether created directly from Shape or from the subclass Circle, runs the Shape constructor body, which increments the shared static counter each time.
C. 1
Assumes only the last instantiation, the direct new Shape(), is counted. The counter accumulates across every constructor call in order, not just the final one, so all three calls add to the same running total.
D. 0
Assumes a static field declared with an initializer never actually changes after the class is defined. The initializer only sets the starting value, the constructor body runs on every instantiation and updates it from there.

A static field belongs to the class itself, and Shape.count is initialized once to 0 when the class is defined. Every time the constructor body runs, whether through new Shape() directly or through new Circle() which inherits the constructor, Shape.count++ executes and updates the one shared value. Three constructions in total bring the counter to 3.

The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 JavaScript questions, 9 euros

Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.