CodeBlanks Logo Icon CodeBlanks

Module pattern - modern comparison

JavaScript course · Expert · Lesson 5/63

Compare the classic module pattern with ES modules and learn when to use each.

The Module pattern - classic

The Module pattern separates private state from a public API. Before ES modules, JavaScript achieved this with an IIFE (immediately invoked function expression) and a closure.

Variables that should not be reached from outside are declared inside the IIFE; only the returned object is exposed.

This creates true private fields.

Comparison with ES modules

Modern JavaScript uses ES modules (export, import) instead of the classic module pattern. File scope gives natural privacy; anything not exported stays private.

You may still see the classic module pattern in old code. For new code ES modules are preferred because browsers and tooling support them natively.

const Counter = (function () {
  let count = 0;
  return { increment() { count++; } };
})();

Exercise Counter module

Write a module named Counter defined with an IIFE. Inside the IIFE keep a private counter with let count = 0. Return an increment() method that increases count by one. Use return to return an object.

Show example solution
Start with const Counter = (function () {, set let count = 0, expose methods with return { increment() { count++; } };, close with })();.
Example solution:
const Counter = (function () {
  let count = 0;
  return {
    increment() {
      count++;
    },
    value() {
      return count;
    }
  };
})();

Test yourself

  1. Complete the IIFE return

    const Counter = (function () {
      let count = 0;
      return { ____() { count++; } };
    })();
    Show answer
    const Counter = (function () {
      let count = 0;
      return { increment() { count++; } };
    })();
  2. How does the classic module pattern keep private state?

    • In a global variable
    • In a closure inside an IIFE
    • In an HTML data attribute
    • In a constant
    Show answer

    In a closure inside an IIFE — Correct! The IIFE closure creates state that cannot be reached from outside.

  3. Match the Module concepts

    IIFE
    Immediately invoked function
    return {}
    Public API
    let count
    Private state
    ES modules
    Modern module system

All lessons in Expert