🟑 MediumFunctionsπŸ“– Theory Question

What are the Module Pattern and the Revealing Module Pattern?

πŸ’‘

Hint

IIFE + closure = private scope; expose only public API; revealing = explicitly name what's public

Full Answer

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 };
})();
πŸ’‘ Before ES modules, this was THE pattern for encapsulation. jQuery, Lodash, and most pre-2015 JS libraries used this. Today, use ES modules instead.

More Functions Questions

🟒 EasyWhat is the difference between call, apply, and bind?β†’πŸŸ’ EasyHow do arrow functions differ from regular functions?β†’πŸŸ’ EasyWhat is a pure function and why does it matter?β†’πŸŸ’ EasyWhat are Higher-Order Functions (HOF)?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint