Skip to main content
Private fields are class properties prefixed with a hash (#) that enforce strict encapsulation at the language level. Unlike the traditional underscore convention (_property), private fields provide “hard privacy”—they are completely inaccessible and invisible outside the lexical scope of the class body in which they are defined.

Syntax and Declaration

Private fields must be explicitly declared in the class body before they can be accessed or mutated. They cannot be dynamically added to an instance at runtime.

Core Mechanics and Rules

1. Strict Lexical Scoping Accessing a private field outside of its defining class results in a SyntaxError. This is evaluated at compile-time, preventing execution entirely.
2. Bracket Notation Incompatibility Private fields cannot be accessed using bracket notation. Attempting to do so will interact with a public string property that happens to start with a hash, rather than the actual private field.
3. Inheritance Restrictions Private fields are bound strictly to the class that defines them. Subclasses cannot access the private fields of their parent classes.

Static Private Fields and Methods

The # prefix can also be applied to static properties and class methods (both instance and static). Static private fields are evaluated on the class constructor itself rather than the instance.

Ergonomic Brand Checks

JavaScript provides a mechanism to safely check if an object possesses a specific private field using the in operator. This is known as a “brand check” and will not throw an error if the field is missing, returning a boolean instead.
Tired of Poor JavaScript Skills? Fix That With Deep Grasping!Learn More