Part 1: The "Revealing Module" Pattern (The OG Secret)

Before JavaScript had a official module system, developers used a trick called the Revealing Module Pattern. It uses an IIFE (Immediately Invoked Function Expression).

In JavaScript, variables inside a function stay inside that function. By returning only an object with specific functions, we "reveal" only what we want the world to see.

const mySecretModule = (() => {
  const privatePin = "1234"; // Nobody can see this!
  const getPin = () => console.log(privatePin);

  return { getPin }; // We only reveal the function, not the variable
})();

Part 2: CommonJS (The Traditional Node Way)

When Node.js first started, it used CommonJS (CJS). You’ve probably seen this using require and module.exports.

Part 3: ES Modules (The Modern Standard)

ESM (ECMAScript Modules) is the official standard for JavaScript today. It uses import and export.

Key differences from CJS:

  1. Static Imports: You must put import at the very top of your file. You can't put it inside an if statement like you can with require.
  2. Read-Only Bindings: In CJS, if you import a variable, you get a copy. In ESM, you get a live link. If the original module changes the value, your version changes too, but you aren't allowed to change it yourself.
  3. Loading Phases: ESM is smarter. It first parses the whole "tree" of your files to see how they connect, then links them, and only then runs the code. This makes it much better at handling "circular dependencies" (when File A needs File B, and File B needs File A).

⚡ 2026 Updates (Modern Node.js Docs)

The book notes some things were experimental in 2020 that are standard now: