All sample questions / JavaScript

JavaScript this, Prototypes and Classes, what does console.log(Named.label()) print after const Named = class MyClass?

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

const Named = class MyClass {
  static label() {
    return MyClass.name;
  }
};
console.log(Named.label());

What does this print?

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

Answer, C. MyClass

A. Named
Assumes the inner name is just an alias for whatever variable the class expression was assigned to on the outside, so it would reflect the outer binding name instead. The name given in a class expression is a separate binding visible only inside the class body, it always refers to the class itself, not to the outer variable it happens to be stored in.
B. ReferenceError
Assumes referencing the internal name from a static method fails because that name is only meant for recursive references and not for general use. The internal binding created by a named class expression works like any normal reference to the class, it can be used for recursion or for anything else, including simply reading its name property.
C. MyClass
Correct. A named class expression makes its own name available inside its body only, so the static method reads MyClass, which is the class own name regardless of the outer variable it was assigned to.
D. undefined
Assumes the internal class name is not actually usable from inside the class own static methods, resulting in a missing value. A named class expression name is fully valid and readable from any method defined in that class body, static or not, exactly like an ordinary function reference.

Writing class MyClass { ... } as an expression assigned to Named creates an internal binding named MyClass that is visible only from within the class body itself, separate from the outer variable Named. Inside label, MyClass refers to the class itself, and its name property reflects that internal name, not the variable it was ultimately stored in. So Named.label() reads MyClass.name, giving the string MyClass.

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.