How can you create private variables in JavaScript using closures?
Declare the variable inside a function and return only functions that use it. The variable lives on in the closure, but no outside code can read or change it directly.
Explain it simply
Think of a bank locker room. You cannot walk into the vault, but the clerk hands you two buttons: deposit and check balance. The money is private; the buttons are the public interface.
In code, the vault is a local variable in a function. When the function returns an object of methods, those methods keep access to the variable through their closure, even though the outer function has finished. Nothing else can reach it, because there is no property to touch.
Modern JavaScript also has class private fields (#balance), but closures work everywhere and are a very common interview question.
Example
function createWallet(start) {
let balance = start;
return {
add(rupees) { balance += rupees; return balance; },
get() { return balance; }
};
}
const w = createWallet(100);
w.add(50);
console.log(w.get()); // Output: 150
console.log(String(w.balance)); // Output: undefinedEach call to createWallet makes a fresh, independent balance.
What to say in the interview
"A closure keeps a function's local variables alive after it returns. By returning only methods that use the variable, I get true privacy without naming conventions. Each call creates a separate private state. Class #private fields are the newer alternative."
Common mistakes
- Exposing the variable as a property (this.balance) and assuming it is private.
- Expecting two wallets to share one balance. Each call gets its own.