Private Fields & Methods (#field)
Private Fields & Methods (#field) in Modern JavaScript
For over two decades, JavaScript lacked true language-level encapsulation. Developers relied on naming conventions (like _underscorePrefix) or closures to simulate privacy. Introduced officially in ES2022, Private Class Fields and Methods (using the # prefix) provide hard, engine-enforced privacy.
1. The Historical Problem: Soft Conventions vs. Hard Privacy
External consumers could inspect and mutate _pin directly, breaking invariants and leaking secrets.
2. Modern Private Fields Syntax: #field
Private fields are declared at the class body level using the # symbol. Attempting to access them outside the class results in a compile-time SyntaxError:
3. Private Methods & Accessors
You can make helper methods, getters, and setters private using #:
4. Subclasses Cannot Access Private Fields!
Private fields are strictly private to the exact class in which they were declared. Derived subclasses cannot access private fields of their parent class:
5. Checking Private Fields with the in Operator (ES2022)
To safely check whether an unknown object contains a private field without throwing errors:
Practice Quiz
Prototypal Inheritance vs Class Inheritance
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Getters, Setters & Static Methods | Prototypal Inheritance vs Class Inheritance |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.