Programming Language
JavaScript
Advanced JavaScript
Design Patterns
Module Pattern

Module Pattern

The Module Pattern is used to encapsulate code, providing a way to have both private and public variables and methods within a single object.


1. The Analogy: The Intercom System

Imagine a high-security Apartment Building.

  • The Inside: There are thousands of items inside the apartments (Private variables). The public cannot see them or touch them.
  • The Intercom: This is the only way you can interact with the building (Public methods). You can press a button to "Speak to Front Desk," but you can't walk into someone's kitchen.

The internal wiring and structure of the building are hidden; you only get the Control Panel (API) that the architect (The Developer) gave you.


2. Coding Example: The Bank Account

You only want someone to change their balance through a deposit or withdraw function, not by directly changing the balance variable.

Module Pattern Implementation

const BankAccount = (function() {
  let balance = 0; // Private variable (Hidden)
 
  return {
    deposit(amount) {
      balance += amount;
      console.log(`Deposited: ${amount}. New balance: ${balance}`);
    },
    getBalance() {
      return balance; // Public way to see private data
    }
  };
})();
 
BankAccount.deposit(100);
console.log(BankAccount.getBalance()); // 100
// console.log(BankAccount.balance); // undefined! You can't touch it directly.

3. Why it matters in Coding

  1. Security: It prevents other parts of your app from accidentally changing sensitive data (like authentication tokens or core settings).
  2. Organization: It keeps related code grouped together, making it easier to read and maintain.
  3. Namespace: It prevents "Variable Collisions" (When two libraries use the same variable name).

Real-Life Coding Scenario: The Auth Module

In a web app, you might have an Auth module. It stores a private token but has a public login() and logout() method. Other developers can call login(), but they can't grab the token directly and send it to their own server.


Summary

ComponentAnalogyTechnical Takeaway
PrivateThe Inside of the ApartmentVariables hidden from the outside.
PublicThe Intercom PanelThe API you expose to the world.

The Module pattern turns your code into a secure, well-guarded vault!