Hint
IIFE + closure = private scope; expose only public API; revealing = explicitly name what's public
Pre-ES-modules patterns for creating encapsulated, private state in JavaScript.
// Module Pattern
const counter = (function() {
let _count = 0; // private β inaccessible from outside
return {
increment() { _count++; },
decrement() { _count--; },
getCount() { return _count; }
};
})();
counter.increment();
counter.getCount(); // 1
counter._count; // undefined β truly private β
// Revealing Module Pattern
// Define everything privately, then reveal selectively
const bankAccount = (function() {
let _balance = 1000;
let _transactions = [];
function _log(type, amount) {
_transactions.push({ type, amount, date: Date.now() });
}
function deposit(amount) {
if (amount > 0) { _balance += amount; _log('deposit', amount); }
}
function withdraw(amount) {
if (amount > 0 && amount <= _balance) {
_balance -= amount; _log('withdrawal', amount);
}
}
function getBalance() { return _balance; }
function getHistory() { return [..._transactions]; }
// Explicitly reveal the public interface
return { deposit, withdraw, getBalance, getHistory };
})();