Private class fields use the # prefix for true encapsulation. Here's how to use them effectively.
Basic Syntax
Private Methods
Private Static Fields
Private Accessors
Checking for Private Fields
Private Fields in Inheritance
Factory Pattern with Privacy
State Machine
Immutable Configuration
Observable with Private State
Best Practices
Usage:
✓ Use # for true privacy
✓ Keep sensitive data private
✓ Hide implementation details
✓ Use private methods for internals
Patterns:
✓ Validation in private methods
✓ State management
✓ Factory methods
✓ Encapsulated logic
Benefits:
✓ True encapsulation
✓ No naming conventions needed
✓ Cannot be accessed externally
✓ Safe from prototype pollution
Avoid:
✗ Private fields in object literals
✗ Accessing via ['#name']
✗ Exposing private data in methods
✗ Over-privatizing everything
Conclusion
Private class fields with # provide true encapsulation in JavaScript. They cannot be accessed or modified from outside the class, making them ideal for sensitive data and internal implementation. Use private methods for validation and internal logic, and remember that each class has its own private namespace even in inheritance.