Skip to content
JavaScript·Intermediate·Coding·1 min read

How are closures used for encapsulation?

Short interview answer

A factory can keep mutable bindings private and expose only functions that operate on them. Consumers cannot access the bindings directly, but returned methods share the same environment. ES private fields are often clearer for class-shaped objects, while closures fit functional APIs.

Example

JavaScript
function createAccount(balance) {  return {    deposit: (n) => (balance += n),    getBalance: () => balance,  };}
const acct = createAccount(100);acct.deposit(50);      // 150acct.getBalance();     // 150acct.balance;          // undefined — no direct access

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Closures

Related questions