TL ; DR:
Modern JavaScript (ES2022+) has true private fields with the
#prefix:class Dog { #name; constructor(name) { this.#name = name; } getName() { return this.#name; } }
Outside the class,
rex.#nameis a syntax error — the runtime enforces it.Older code uses the underscore convention (
this._name), which is just a hint and not enforced.
Full lesson:
For decades, JavaScript classes had no real privacy — programmers used a leading underscore (_name) as a convention. ES2022 added true private fields with the # prefix.
How # private fields work
- You must declare the field at the top of the class body:
#name; - You access it as
this.#name— never as a string or viathis[...]. - Trying to access from outside is a syntax error, not a runtime error.
Your task
The Dog class declares #name and the constructor stores into it. Add a getName() method that returns this.#name.
Dog's name: RexFree plan: 30 tutor messages. PRO is unlimited.
