Private Methods Pattern
You'll learn: How to hide helper functions inside a factory function so that only the returned object can use them — keeping internal logic truly private.
The Core Idea
The Private Methods Pattern uses closures to create helper functions that exist only within the factory function's scope. These helpers can't be accessed from outside, but the methods on the returned object can call them freely. It's like having backstage staff that the public never sees, but your public-facing team uses all the time.
How It Works
Define regular functions inside your factory function, then have your public methods reference them via closure:
function createUser(name) {
// Private helper - not returned
function validateName(n) {
return n && n.length > 0;
}
// Private helper - not returned
function formatName(n) {
return n.trim().toLowerCase();
}
let userName = name;
return {
getName() {
return userName;
},
setName(newName) {
if (validateName(newName)) {
userName = formatName(newName);
return true;
}
return false;
}
};
}
const user = createUser("Alice");
user.setName(" BOB "); // uses both private helpers
console.log(user.getName()); // "bob"
console.log(user.validateName); // undefined - private!
The validateName and formatName functions are completely invisible outside. Only getName and setName exist on the returned object, but they leverage the hidden helpers through closure.
Why This Matters
This pattern keeps your internal logic safe from external tampering. You control exactly what's public (the API) and what's implementation detail (the helpers). It reduces surface area for bugs and makes refactoring internals easier.
Key Takeaway: Private methods are regular functions defined inside a factory that aren't returned but remain accessible to public methods via closure — perfect for hiding implementation details.