JavaScript · Closures · Junior · Concept
How can closures create private state, and when is that useful?
Short Interview Answer
Hide variables in an outer function and expose only methods that close over them — encapsulation without classes.
Detailed Explanation
Variables in the outer function are not accessible from outside unless returned or attached to an exported API. Returned methods share that environment, so they can read/write private state while callers cannot reach the raw bindings. This pattern underpins revealing module patterns, store factories, and many library APIs. Compared with `#private` class fields, closure privacy works on plain functions and does not appear on the instance as enumerable properties. Trade-off: each factory call creates new function objects, which can matter at huge scale.
Example
function createBankAccount(opening) {
let balance = opening;
return {
deposit(n) { balance += n; },
getBalance() { return balance; },
};
}
const acct = createBankAccount(100);
// balance is not accessible directlyInterview Tip
Mention the per-instance function allocation cost vs prototype methods.
Common Mistake
Claiming closure 'privacy' is cryptographic security — it is encapsulation, not a security boundary against determined attackers in the same realm.