When to Use Each Access Level
You'll learn: How to choose the right visibility modifier (public, private, protected, or #) based on your encapsulation needs.
The Decision Framework
Choosing the right access level is about controlling who can touch what. Each modifier serves a different trust boundary in your code.
Think of a building: public areas are the lobby anyone can enter, private rooms have keys only you hold, protected spaces are accessible to you and your family (subclasses), and # private is like a biometric lock that can't be picked even at runtime.
When to Use public
Default choice for your API surface. Use public (or omit the modifier) when a property or method is meant to be used by external code:
class BankAccount {
public accountNumber: string; // ✓ Users need this
public deposit(amount: number) { // ✓ Core API
// ...
}
}
If something is part of "how this class is used," make it public.
When to Use private
Implementation details that might change. Use private for internal helpers and state that external code should never touch:
class BankAccount {
private balance: number = 0; // ✗ Direct manipulation would break validation
private validateAmount(amount: number) { // ✗ Internal helper
return amount > 0;
}
}
Think: "If I change this next week, who breaks?" If the answer is "only this class," use private.
When to Use protected
Shared implementation across inheritance hierarchies. Use protected when subclasses need access, but external code doesn't:
class Account {
protected logTransaction(message: string) { // Subclasses can log
console.log(message);
}
}
class SavingsAccount extends Account {
addInterest() {
this.logTransaction("Interest added"); // ✓ Works
}
}
If you're not using inheritance, you probably don't need protected.
When to Use # Private Fields
True runtime privacy and no naming conflicts. Use # when you need hard privacy that survives JavaScript runtime:
class SecureVault {
#encryptionKey: string; // Truly inaccessible at runtime
}
Also useful in mixins or multiple inheritance patterns where private could have naming collisions.
Practical Decision Tree
- Is it part of the public API? →
public - Should subclasses access it? →
protected - Need runtime privacy or avoiding conflicts? →
#private - Everything else (internal implementation)? →
private
Key Takeaway: Start with private for everything internal, use public for deliberate API surfaces, reserve protected for inheritance scenarios, and reach for # when you need runtime guarantees or conflict avoidance.