JavaScript Modules Explained: Why Modules Exist, IIFEs, Closures and CommonJS require
Why JavaScript needs modules, how developers built them from closures and IIFEs, how bundlers wrap files, and how Node's CommonJS works: require, exports vs module.exports, the module wrapper, caching, resolution, circular dependencies and copied values.
kvi5hnuCode Sprout team member8 min readOn this page
A real application is thousands of lines written by many people, plus dozens of libraries written by strangers. If every function and variable lived in one shared global namespace, two files that both define format or config would silently overwrite each other. Modules solve this: each file gets its own private scope and explicitly chooses what to export and what to import.
JavaScript went through three module systems:
- Do-it-yourself modules built from objects, closures and IIFEs (this article).
- CommonJS, Node's
require()system, still everywhere in the npm ecosystem (this article). - ES modules (
import/export), the official standard, supported natively by browsers and Node (next two articles).
New code should use ES modules, but you'll meet the other two constantly in existing code, in library source, and in interview questions, and they explain why ES modules work the way they do.
The problem: one global scope
In a browser, classic <script> files share the global scope:
// file: cart.js (a classic script)
var total = 0;
function format(n) { return "$" + n.toFixed(2); }
// file: report.js (another classic script, loaded later)
var total = "Q3"; // silently replaces cart.js's total
function format(d) { return d.toISOString(); } // and its format function
Nothing warns you. The last script loaded wins, and cart.js breaks in ways that are hard to trace. Libraries tried to cope by using a single global object, like Math groups its functions or how jQuery used just $.
Namespace objects
The first step is to put everything under one object, so only one global name is used:
const Shop = {
taxRate: 0.08,
format(n) {
return "$" + n.toFixed(2);
},
withTax(n) {
return this.format(n * (1 + this.taxRate));
},
};
console.log(Shop.withTax(10));
Shop.taxRate = 5; // ...but anyone can change anything
console.log(Shop.withTax(10));
$10.80
$60.00
That reduces name clashes but hides nothing: every helper and setting is public and writable.
IIFE modules: closures for privacy
An immediately invoked function expression (IIFE, article 66) creates a private scope, runs once, and returns only the public API. Its local variables stay private but alive, thanks to closures (article 67). This is the classic module pattern:
const stats = (function () {
// private: invisible outside this function
const sum = (a, b) => a + b;
const square = (x) => x * x;
// public
function mean(values) {
return values.reduce(sum) / values.length;
}
function variance(values) {
const m = mean(values);
return values.map((v) => square(v - m)).reduce(sum) / values.length;
}
return { mean, variance }; // the module's exports
})();
console.log(stats.mean([2, 4, 6, 8]), stats.variance([2, 4, 6, 8]));
console.log(typeof stats.sum, typeof sum);
5 5
undefined undefined
sum and square can't be reached or overwritten from outside. Before 2015, most libraries were written this way, often with a twist that passed dependencies in as arguments: (function ($, window) { ... })(jQuery, window);.
How bundlers turn files into modules
Wrapping every file by hand is tedious, but it's mechanical, so tools did it automatically. A bundler (Browserify, then webpack, Rollup, esbuild, Vite) reads your files, wraps each in a function, and combines them into one file with a tiny module loader. Simplified, the output looks like this:
const moduleFactories = {
"./math.js"(exports, require) {
exports.double = (n) => n * 2;
},
"./main.js"(exports, require) {
const { double } = require("./math.js");
console.log("double(21) =", double(21));
},
};
const cache = {};
function require(name) {
if (!(name in cache)) {
const exports = {};
cache[name] = exports; // cache before running (for cycles)
moduleFactories[name](exports, require); // run the file's code once
}
return cache[name];
}
require("./main.js");
double(21) = 42
That's essentially the CommonJS model: each file is a function with its own scope; require runs a file once, caches its exports, and returns them.
CommonJS: Node's module system
Node adopted this model in 2009. In a CommonJS file (a .js file in a package without "type": "module", or any .cjs file):
- every file is a module with its own scope;
require(specifier)loads another module and returns its exports;- the file exports values by adding properties to
exportsor by replacingmodule.exports.
// file: stats.js
const sum = (a, b) => a + b; // private
exports.mean = (values) => values.reduce(sum) / values.length;
exports.max = (values) => Math.max(...values);
// file: main.js
const stats = require("./stats.js"); // the whole exports object
const { max } = require("./stats.js"); // or destructure what you need
console.log(stats.mean([1, 2, 3]), max([1, 2, 3])); // 2 3
To export a single value (a function or a class), replace module.exports:
// file: logger.js
module.exports = class Logger {
log(message) { console.log(`[log] ${message}`); }
};
// file: app.js
const Logger = require("./logger.js");
new Logger().log("started");
exports vs module.exports

Node gives each module an object module, with module.exports initially set to {}, and a local variable exports that points to the same object. require always returns module.exports. So:
exports.x = 1adds to the shared object: works.module.exports = somethingreplaces what's exported: works.exports = { x: 1 }only reassigns the local variable: exports nothing.
You can reproduce this exactly with an ordinary function, because that's all a CommonJS module is:
function runModule(body) {
const module = { exports: {} };
body(module.exports, module); // Node passes (exports, require, module, ...)
return module.exports; // what require() returns
}
console.log(runModule((exports) => { exports.hello = "hi"; }));
console.log(runModule((exports) => { exports = { hello: "hi" }; }));
console.log(runModule((exports, module) => { module.exports = { hello: "hi" }; }));
{ hello: 'hi' }
{}
{ hello: 'hi' }
A safe habit: use module.exports = { ... } once at the end of the file, or only ever add properties to exports. Don't mix the two.
The module wrapper
Node runs every CommonJS file inside a function like this:
(function (exports, require, module, __filename, __dirname) {
// your file's code
});
That explains several facts at once:
- Top-level variables are local to the file, not global.
exports,require,module,__filename(this file's absolute path) and__dirname(its folder) are available without importing anything: they're the wrapper's parameters.- At the top level of a CommonJS file,
thisismodule.exports, not the global object (and notundefinedas in ES modules). returnat the top level is legal (it returns from the wrapper).
Modules run once and are cached
The first require of a file runs it and caches the result. Later require calls, from any file, return the same exports object without running the code again:
// file: counter.js
console.log("counter.js runs");
let count = 0;
module.exports = { increment() { count++; }, getCount: () => count, count };
// file: main.js
const a = require("./counter.js"); // prints "counter.js runs"
const b = require("./counter"); // nothing printed: cached (.js is optional)
console.log(a === b); // true
a.increment();
a.increment();
console.log(a.getCount(), a.count); // 2 0
Caching makes modules natural singletons: a shared database connection or configuration object created in one module is shared by every file that requires it. The cache is visible as require.cache; deleting an entry forces a reload (occasionally used in tests).
Note the last line: a.count is still 0. CommonJS exports values: count was copied into the exports object when it was created, and later changes to the local count variable don't affect that copy. Functions like getCount() that read the variable on each call see the current value. ES modules behave differently here (next article).
How require finds files
- Built-in modules:
require("node:fs"),require("node:path"). Thenode:prefix is optional for most built-ins but recommended, since it's unambiguous and can't be shadowed by an npm package. - Relative paths:
require("./utils/format.js")orrequire("../config"), resolved from the current file's folder (not the working directory). Node tries the exact name, then adds.js,.jsonand.node, then looks forindex.jsin a folder. - Package names (bare specifiers):
require("express")searchesnode_modulesfolders, starting next to the current file and moving up through parent folders. The package'spackage.jsondecides which file is the entry point ("main"or the newer"exports"field). - JSON:
require("./data.json")parses the file and returns the data.
require is synchronous: it reads and runs the file before returning. That's fine on a server's local disk, but it's why CommonJS couldn't work directly in browsers, which must fetch files over the network.
Circular dependencies
When a.js requires b.js and b.js requires a.js, Node doesn't loop forever: the second require("./a.js") returns a's exports as they are so far, which may be incomplete:
// file: a.js
exports.ready = false;
const b = require("./b.js");
console.log("in a, b.ready =", b.ready);
exports.ready = true;
// file: b.js
exports.ready = false;
const a = require("./a.js"); // a.js is only half-done
console.log("in b, a.ready =", a.ready);
exports.ready = true;
Running node a.js prints:
in b, a.ready = false
in a, b.ready = true
Cycles usually signal that shared code should move into a third module. If you can't avoid one, access the other module's exports lazily (inside functions that run later) rather than at load time, and don't replace module.exports in modules involved in a cycle, since the other side may already hold the old object.
CommonJS today
CommonJS isn't going away soon: a large share of npm packages and older Node apps use it, and tools like Jest supported it first. But it's a Node convention, not part of the JavaScript language; it loads synchronously, and its exports can only be fully known by running the code, which limits tools that remove unused code. ES modules fix all three issues, and current Node versions let the two systems interoperate (article 76).
Common questions
What's the difference between exports and module.exports?
module.exports is the object require returns. exports is a local variable that initially points to the same object, as a shortcut for adding properties. Reassigning exports breaks that link and exports nothing; reassign module.exports instead.
Does requiring the same module twice run it twice?
No. Modules run once; the result is cached by resolved filename, and every later require returns the same object.
What's an IIFE module, and is it still used?
A function expression that runs immediately and returns a public API, keeping everything else private in its closure. Hand-written ones are rare today, but bundlers still produce code shaped like this, and you'll see it in older libraries and UMD builds.
What is UMD?
"Universal Module Definition": a wrapper pattern that detects whether CommonJS, AMD (an older browser loader) or plain globals are available and exports accordingly. Library builds used it so one file worked everywhere. ES modules have made it largely unnecessary.
Summary
- Modules give each file a private scope and explicit exports and imports, preventing global name clashes.
- Before standard modules, namespace objects reduced clashes and IIFEs added privacy through closures; bundlers automated this wrapping.
- CommonJS (
require,exports,module.exports) is Node's original system: files run inside a wrapper function, once, and are cached. requirereturnsmodule.exports; reassigningexportsexports nothing.requireresolves built-ins, relative paths andnode_modulespackages synchronously; circular requires see partially filled exports.- CommonJS exports are values copied at export time; read changing state through functions.
Practice Questions
What does require("./m.js") return if m.js contains only this code?
exports = { a: 1 };
exports.b = 2;
Answer
{}. After exports is reassigned, it no longer points to module.exports, so both assignments affect only the new local object.
A module config.js builds a settings object at load time. Three other files require it, and one changes a setting. Do the others see the change?
Answer
Yes. The module ran once, and all three got the same cached object, so a mutation is visible everywhere. That's useful for shared state but can cause surprising coupling.
Rewrite this script as an IIFE module that keeps items private and exposes add and count:
var items = [];
function add(x) {
items.push(x);
}
function count() {
return items.length;
}
Answer
const inventory = (function () {
const items = [];
return { add(x) { items.push(x); }, count() { return items.length; } };
})();
In a CommonJS file, what are this and typeof __dirname at the top level?
Answer
this is module.exports (initially {}), and typeof __dirname is "string": both come from the module wrapper function.
Previous: Composition over Inheritance in JavaScript: Delegation, Mixins and Abstract Classes
Next: ES Modules in JavaScript: import, export, Default vs Named Exports, Re-exports and Live Bindings

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.