When to Use Private Fields
You'll learn: How to decide whether to use true private fields (#) or stick with naming conventions (_) for encapsulation in your classes.
The Privacy Decision
Private fields (#name) give you hard privacy — no external code can access them, period. Naming conventions (_name) signal "please don't touch" but remain technically accessible. Neither is inherently "better" — the right choice depends on your needs.
When True Privacy Matters
Use # private fields when:
- Security-sensitive data: Authentication tokens, encryption keys, or internal state that must never leak
- Public APIs or libraries: When your code will be used by others who might accidentally (or intentionally) access internal state
- Critical invariants: Internal state that, if modified externally, would break your object's integrity
- Framework or plugin systems: Where untrusted code might run alongside yours
class SecureSession {
#token;
#userId;
constructor(token, userId) {
this.#token = token;
this.#userId = userId;
}
// No way for external code to access #token
}
When Convention Is Enough
Use _name convention when:
- Internal projects: Where your team follows conventions
- Debugging needs: Want visibility in devtools or during testing
- Legacy codebases: Where private fields aren't supported yet
- Flexibility over security: Privacy is about organization, not protection
class InternalCache {
_data = new Map();
// Accessible if needed, but signals "internal use"
}
The Middle Ground
Sometimes you'll combine both: use _ for "soft private" helpers and # only for truly sensitive data.
Key Takeaway: Use private fields (#) when you need guaranteed encapsulation for security or API stability; use conventions (_) when you need flexibility and trust your codebase to respect boundaries.