Module Pattern — Design Patterns

The Module pattern wraps code in a private scope and only exposes the parts that are needed. Its old form is the IIFE: (function () { let count = 0; return {…

The last lesson named one pain in the first Kancil Courier code: lastTrackingNo can be overwritten by another file. The most basic cure for that in JavaScript is the Module pattern, which wraps code into one unit with two parts. The private part can only be touched from the inside. The public part is handed out on purpose.

Picture a courier's counter. Customers can only talk through the counter window: "send a parcel", "check a tracking number". The tracking-number ledger sits behind the desk, and no customer can cross out a number in it. In code, the window is the object that gets returned, and the ledger is the variable hidden inside a function.

The problem: every file shares one global space

In the old Kancil Courier, each file is loaded with a plain <script>. A var at the top level of a file like that goes into one global space shared by every file. Two files that happen to use the name count really hold one and the same variable:

// tracking.js
var count = 0
function nextTrackingNo() {
  count = count + 1
  return "KCL-" + String(count).padStart(4, "0")
}

// promo.js (written by someone else, for the daily promo quota)
var count = 0
function resetPromo() {
  count = 0 // only meant to reset the promo quota
}

// main.js
console.log(nextTrackingNo()) // KCL-0001
resetPromo()
console.log(nextTrackingNo()) // KCL-0001 again!

resetPromo zeroes the tracking counter too, so two parcels get the tracking number KCL-0001. No error, just two parcels mixed up at the warehouse.

IIFE: a module made of a closure

Before JavaScript had import and export, the way to make a private space was a function. A variable made inside a function can't be touched from outside it:

const tracking = (function () {
  let count = 0 // private: only the functions in here can touch it

  function nextTrackingNo() {
    count = count + 1
    return "KCL-" + String(count).padStart(4, "0")
  }

  return { nextTrackingNo } // public: only this is handed out
})()

console.log(tracking.nextTrackingNo()) // KCL-0001
console.log(tracking.nextTrackingNo()) // KCL-0002
console.log(tracking.count)            // undefined

The shape "write every function inside, then return an object naming the ones to open up" has its own name: the Revealing Module pattern. If promo.js is wrapped the same way, its count becomes a different variable, and resetPromo() can no longer touch the tracking numbers.

ES modules: the pattern turned into a language feature

Modern JavaScript has built-in modules. Every module file has its own space: variables at the top level of that file are private, and other files can only use what is exported.

// tracking.js
let count = 0 // not exported, so only this file can touch it

export function nextTrackingNo() {
  count = count + 1
  return "KCL-" + String(count).padStart(4, "0")
}

// main.js
import { nextTrackingNo } from "./tracking.js"

console.log(nextTrackingNo()) // KCL-0001

The Playground on this page runs one script, not several files, so the examples you can run there use the IIFE shape.

When not to wrap

⚠️ Small slips that break the module

TL;DR: The Module pattern wraps code in a private scope and only exposes the parts that are needed. Its old form is the IIFE: (function () { let count = 0; return { nextTrackingNo } })(), a function called once straight away, with count safe inside the closure and tracking.count being undefined. Its modern form is the ES module: variables at the top level of a file are private, only what is exported is public, and a module runs once. The problem it removes: global variables overwriting each other, like resetPromo() making the tracking number KCL-0001 come out twice. Don't forget the () at the end of an IIFE, and hand out functions, not copies of numbers.

⚡ One global space, one count

Write:

// main.js
console.log(nextTrackingNo()) // KCL-0001
resetPromo()
console.log(nextTrackingNo())
Guess first: tracking.js and promo.js both have var count. What does the second nextTrackingNo() print?

KCL-0001 again. The two files hold one and the same variable, so resetPromo() zeroes the tracking counter too. No error, just two parcels mixed up.

Meaning: A var at the top level of a plain <script> goes into one global space that every file shares.

⚡ IIFE: the private part stays inside

Write:

const tracking = (function () {
  let count = 0 // private: only the functions in here can touch it

  function nextTrackingNo() {
    count = count + 1
    return "KCL-" + String(count).padStart(4, "0")
  }

  return { nextTrackingNo } // public: only this is handed out
})()

Meaning: The Module pattern wraps code in a private scope and only opens up the parts that are needed. The () at the end calls the function once, and tracking.count gives undefined. Forget that () and tracking.nextTrackingNo isn't a function.

⚡ ES modules: the pattern as a language feature

Meaning: Every module file has its own space. Variables at the top level of the file are private, only what is exported is public, and a module runs once. Need the number from outside? Hand out a function like getCount(), not a copy of the number.

What you will learn