Module
In one line
A module is a self-contained file of code that can export values and import them from other modules.
In simple words
A module is a file of JavaScript code that encapsulates its contents and can share specific parts with other files. You mark what is public with export and consume it elsewhere with import. This lets you split a large program into small, focused files.
Before native modules, JavaScript relied on patterns like IIFEs and libraries such as CommonJS (require) or AMD. ES modules (ESM) are the native standard: export function add() in one file, import { add } from "./math.js" in another. Modern browsers and Node.js both support ESM.
Modules have their own scope — top-level variables in a module are not global. Each module is imported at most once, even if multiple files import it, so its top-level code runs a single time. This makes modules a clean way to organize and reuse code.
Example
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from "./math.js";
console.log(add(2, 3)); // 5math.js exports add; main.js imports it. Each file is a module with its own scope.
Common confusions
Confused with: package
The difference: A module is a single file (or folder with an entry point) of code you import; a package is a distributable unit (often from npm) that may contain many modules plus metadata. All packages contain modules, but a module is not necessarily a package.
Related terms
Related Resources
Related Lessons
- JavaScript Overview
Modules are part of modern JavaScript
Learn the fundamentals
Deepen your understanding with structured lessons on this topic.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.