Sub topic 14
Module Scope in ES Modules
This chapter assumes you know how the global scope works in classic scripts, how the scope chain resolves names, and what strict mode does to undeclared assignments. You also need Node.js 14 or later, or a browser that can load <script type="module">.
A Scope Between Global and Function
An ES module is a file that uses import or export and is loaded as a module. Each module gets its own module scope. Every top-level declaration in the file lives in that scope: var, let, const, class, and function. The module scope sits just inside the global scope, so code in the module can still see globals such as console or Math. Nothing declared at the top of the module leaks out to other files unless you export it.
In a classic script, a top-level var or function declaration becomes a property of globalThis. In a module, it does not.
What Changes at the Top Level
Modules differ from classic scripts in four ways that affect scope:
| Behavior | Classic script | ES module |
|---|---|---|
| Top-level `var` | Property of `globalThis` | Private to the module |
| Top-level `this` | `globalThis` (sloppy mode) | `undefined` |
| Strict mode | Opt-in with `"use strict"` | Always on |
| Undeclared assignment | Creates a global (sloppy mode) | Throws `ReferenceError` |
Strict mode is always on in modules, so the accidental-global bug from the previous chapter cannot happen inside them.
Imports Are Live, Read-Only Bindings
An import gives you a binding, not a copy. The name you import points at the exporting module's variable. If the exporter changes that variable, every importer sees the new value. The importer can't assign to the name itself.
Save these two files in the same folder:
// counter.mjs
export let count = 0;
export function increment() {
count += 1;
}// main.mjs
import { count, increment } from "./counter.mjs";
console.log(count); // 0
increment();
console.log(count); // 1 (live binding, not a copy)
try {
count = 10;
} catch (e) {
console.log(e.name); // "TypeError"
}
var notGlobal = "module-private";
console.log(globalThis.notGlobal); // undefined
console.log(this); // undefined
try {
leaked = 1;
} catch (e) {
console.log(e.name); // "ReferenceError"
}Run it with node main.mjs. The .mjs extension tells Node to treat each file as a module.
Imports Are Hoisted Too
Before any module code runs, the engine reads every import declaration in the whole module graph, loads the dependencies, and links the bindings. As a result, imports act as if they sit at the very top of the file, wherever you wrote them:
// hoisted-import.mjs
console.log(Math.max(1, 2)); // 2, ordinary global
console.log(sep); // "/" on macOS and Linux, "\\" on Windows
import { sep } from "node:path";This hoisting is a side effect of the module loading process, which works like the creation phase you saw earlier. Even so, put imports at the top of the file so readers don't have to know this rule.
Common Mistakes
- Expecting a top-level
varto be shared. Another module or an inline script can't see it. Export it, or setglobalThis.nameexplicitly if you really need a global. - Reassigning an import. Change the value through a function the exporter provides, as
incrementdoes above. - Relying on
thisat the top level. It isundefined. UseglobalThiswhen you need the global object.
Exercise
In a module named config.mjs, the top level contains var mode = "dev";. Another module runs import "./config.mjs"; console.log(globalThis.mode);. What gets logged, and how would you make mode available to the second module the right way?
Show answer
It logs undefined, because a top-level var in a module stays in that module's scope and is not added to globalThis. The right fix is to write export const mode = "dev"; in config.mjs and import { mode } from "./config.mjs"; in the second module.
Exercise
counter.mjs exports let count = 0 and a function reset() that sets count to 0. main.mjs imports count, calls increment() twice, then calls reset(). What does console.log(count) print in main.mjs, and why?
Show answer
It prints 0. The import is a live binding to the exporter's variable, so main.mjs sees the value that reset() assigned inside counter.mjs.