Protecting State With # Fields and get

Priya Nair has three swims left on her Riverside Pool card. Booking code needs to read that count, but changes must follow the card’s rules. You’ll keep the count private, expose it for reading, and allow the desk to make corrections within the ten-swim limit.

Protect the Remaining Swims

The leading underscores in Python’s self._swims_left and JavaScript’s this._swimsLeft indicate privacy by convention only. Python name-mangles __swims_left, while JavaScript treats this.__swimsLeft as an ordinary public property.

A JavaScript private field belongs to the class’s internal state. Declare #swimsLeft; inside the class body, then use this.#swimsLeft inside its methods. The language enforces this boundary, so outside booking code can’t access the count directly.

Omitting that declaration before assigning this.#swimsLeft prevents the file from running and raises SyntaxError: Private field '#swimsLeft' must be declared in an enclosing class. Outside the class, priya.#swimsLeft also raises a SyntaxError.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.