Start learning free

LESSON 628 OF 671 · OBJECT-ORIENTED PROGRAMMING

Private Fields in JavaScript

Lesson

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.#name is 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 via this[...].
  • 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: Rex
STEP 1 OF 2
    Ctrl + Enter to check