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
(function () { ... })is a function with no name, wrapped in parentheses so it is read as a value.- The
()at the end calls that function straight away, once. This shape is called an IIFE (Immediately Invoked Function Expression). The arrow version is the same:(() => { ... })(). countlives inside that function.nextTrackingNocan still use it after the outer function has finished running. A function that carries the variables from where it was made like this is called a closure.return { nextTrackingNo }hands out an object holdingnextTrackingNoonly.countisn't handed out, sotracking.countgivesundefined.
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
- A file is a module when it is loaded with
<script type="module">,imported by another module, or put together by a bundler such as Vite. promo.jsmay have its ownlet count. Same name, but each file has its own space, so nothing gets overwritten.- A module runs only once. Every file that
importstracking.jsuses the samecount. That sets up the Singleton lesson.
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
- A function with no state.
formatPrice(n), which only works from its parameter, has nothing to hide. In a modern project,export function formatPriceis enough. - An IIFE inside an ES module. A module file is already private. Wrapping it again in an IIFE only adds a layer of parentheses.
- Needing many separate counters. An IIFE runs once and makes one object. If every warehouse needs its own counter, write a plain function (
function makeCounter() { ... }) and call it as often as you need.
⚠️ Small slips that break the module
varin a plain<script>. A variable at the top level of such a file is global and can be overwritten by another file using the same name. Wrap it in an IIFE, or use ES modules.- Forgetting the
()at the end of an IIFE.const tracking = (function () { ... })stores the function, not its result.tracking.nextTrackingNo()then fails withTypeError: tracking.nextTrackingNo is not a function. return { count, nextTrackingNo }. Thecountin that object is only a copy of the number at the momentreturnruns. AfternextTrackingNo()twice,tracking.countis still0. If the number has to be read from outside, hand out a function:getCount() { return count }.
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.