Private Methods in JavaScript
🔍 What Are Private Methods?
In JavaScript, private methods are functions defined inside a class that are accessible only within that class. Like private fields, they are prefixed with a # and cannot be accessed from outside the class or its subclasses.
Note
💡 Private methods help in hiding implementation details and keeping your class API clean and minimal.
📌 Why Use Private Methods?
- 🛡️ Prevent external access to internal logic
- 🧼 Keep class APIs clean and focused
- 🔧 Enable internal helpers used only within the class
🔧 Syntax of Private Methods
Private Method Example
class Counter {
#count = 0;
#log() {
console.log("Current count:", this.#count);
}
increment() {
this.#count++;
this.#log(); // ✅ valid access
}
}
const c = new Counter();
c.increment(); // "Current count: 1"
c.#log(); // ❌ SyntaxErrorNote
⚠️ Attempting to call a private method from outside the class using c.#log() will result in a SyntaxError.
💡 Use Cases
Private methods are especially useful for:
- 🔁 Internal utility methods that should not be exposed
- 🔒 Security-sensitive operations
- 🧪 Keeping logic encapsulated and testable only through public APIs
🧪 Example: Password Validator
Private Validation Method
class User {
#password;
constructor(password) {
this.#password = password;
}
#isValidPassword(pwd) {
return pwd === this.#password;
}
login(input) {
return this.#isValidPassword(input)
? "Access granted"
: "Access denied";
}
}
const user = new User("secret123");
console.log(user.login("secret123")); // Access granted
console.log(user.#isValidPassword("test")); // ❌ SyntaxError🔬 Comparison: Public vs Private Methods
| Method Type | Accessibility | Use Case |
|---|---|---|
| Public | Everywhere (outside & inside class) | Class API |
| #Private | Only inside the class | Internal utilities or logic |
📚 Further Reading
>>“Hide implementation details — reveal intentions. Good design is not what you add, it’s what you hide.” 💡