module
A module is a JavaScript file whose top-level code runs in its own scope, so it shares values with other files only through the names it explicitly exports and they explicitly import.
Modules split a program into files that each own one job, such as a data layer or a set of helpers. A module’s top-level declarations stay private to its scope instead of becoming globals. Other modules reach them through export and import declarations.
JavaScript has two module systems in wide use. ES modules (ESM) are the standard system that ECMA-262 has defined since ES2015, and browsers and Node.js both run them. CommonJS is the older Node.js system built on require() and module.exports.
ES modules follow a few rules that classic scripts don’t. Module code is always in strict mode, and top-level this is undefined. An imported name is a live, read-only binding to the exporter’s variable, so the importer sees every later change but can’t reassign it.
Hosts such as browsers and Node.js load each module once per resolved URL. A module’s top-level code therefore runs a single time, no matter how many other modules import it, and every importer shares its state, as the example below shows:
Example
Say an app counts page visits in one module, and two other modules record visits through it. The counter module logs a line when it starts running:
counter.mjs
console.log("Evaluating counter.mjs");
export let visits = 0;
export function recordVisit() {
visits += 1;
}
The home page module records one visit:
home.mjs
import { recordVisit } from "./counter.mjs";
recordVisit();
console.log("Home page recorded a visit");
The entry module loads the home page, records a second visit, and then tries to reset the counter:
app.mjs
import "./home.mjs";
import { recordVisit, visits } from "./counter.mjs";
recordVisit();
console.log(`Visits: ${visits}`);
console.log(`Top-level this: ${this}`);
visits = 0;
Running the entry module shows the counter’s top-level code running once:
$ node app.mjs
Evaluating counter.mjs
Home page recorded a visit
Visits: 2
Top-level this: undefined
TypeError: Assignment to constant variable.
Both home.mjs and app.mjs import counter.mjs, but its log line appears once, so the two modules share one visits variable. The imported visits reports both calls because it’s a live binding. The final assignment throws, because only the exporting module can change visits.
Related Resources
Course
JavaScript Modules and Scripts for Pythonistas
Port a school's Python boiler log digest to JavaScript, and learn how to import from your own modules, run a module as a script with arguments, and read and write files.
For additional information on related topics, take a look at the following resources:
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 18, 2026