Why can't `#private` fields return undefined before initialization?

Private fields don't have a temporal dead zone, they simply don't exist on the instance until base class constructor finishes executing. They can't be installed before that point because the base constructor is the thing which creates the object in the first place.

As a general rule, you should avoid calling derived methods in base class constructors. Derived methods can (as in this case) rely on state which the derived class constructor sets up, and that hasn't happened when the base class constructor is running. This is true in every OO language; it's a good rule to learn.

As to your particular suggestion, falling back to undefined for private fields which haven't been set up wouldn't help in most cases, because you'd usually actually need to know what the value of the field should be. If you're just using the fallback to undefined to be defensive against running before the derived class constructor has executed, you can use if (#x in this) { ... } instead of if (this.#x === void 0) { ... }.

2 Likes