Sub topic 14
Module Scope in ES Modules
This chapter assumes you already know the earlier material in this tutorial: lexical scope, the global scope, block scope with let and const, the temporal dead zone (TDZ), closures, and strict mode. You also need to run multi-file code. In Node.js, save each file with the .mjs extension. In a browser, load the entry file with a script tag whose type attribute is set to "module".
An ES module is a JavaScript file loaded with import and export. Each module gets its own scope, called module scope. It sits between the global scope and any function or block scopes inside the file. Top-level names in a module are visible everywhere in that file and nowhere else unless you export them.
Where Module Scope Sits in the Scope Chain
In a classic script, top-level declarations go straight into the global scope. Two scripts on the same page share those names and can overwrite each other. A module adds one more layer. When the engine looks up a name inside a module, it checks the local scopes first, then the module scope, then the global scope.
The arrows show the direction of lookup. No arrow connects a.mjs to b.mjs. A module can read another module's names only through import.
Top-Level Declarations Stay Private
In a classic script, a top-level var becomes a property of globalThis. In a module it does not. The same is true for function declarations.
// scope-demo.mjs
var appName = "inventory";
let version = 2;
function helper() {
return "help";
}
console.log(appName); // "inventory"
console.log(globalThis.appName); // undefined
console.log(globalThis.version); // undefined
console.log(typeof globalThis.helper); // "undefined"Run it with node scope-demo.mjs. All three names are usable inside the file, but none of them reach the global object. Inside a module, var still follows function-scoping rules and still hoists with the value undefined. Its top level simply belongs to the module, not to the global object.
If you really need a global, assign one on purpose:
// make-global.mjs
globalThis.APP_CONFIG = { debug: true };
console.log(APP_CONFIG.debug); // trueThe lookup for APP_CONFIG misses the module scope and finds the name on the global object. This works, but it gives back the isolation modules provide. Exporting the value is usually the better choice.
Modules Are Always Strict
Module code runs in strict mode automatically. You do not write "use strict", and you cannot turn strict mode off. That has two direct effects on scope.
// strict-demo.mjs
try {
leaked = 1; // no declaration
} catch (e) {
console.log(e.name); // "ReferenceError"
}
console.log(this); // undefinedFirst, the accidental-global bug from the previous chapter cannot happen. Assigning to an undeclared name throws instead of creating a global property. Second, this at the top level of a module is undefined. In a classic browser script it is window, and in a Node.js CommonJS file it is module.exports. Code that relies on top-level this to reach the global object breaks when you move it into a module. Use globalThis instead.
Classic Scripts, CommonJS, and ES Modules Compared
Node.js has an older module system, CommonJS (require and module.exports). It also keeps top-level names private, but it does so differently: Node.js wraps each CommonJS file in a function, so its top level is really a function scope. The table compares the three.
| Behavior | Classic script | CommonJS file | ES module |
|---|---|---|---|
| Top-level `var` on `globalThis` | Yes | No | No |
| Top-level `let`/`const` visible to other files | Yes, shared global lexical scope | No | No |
| Strict mode | Opt-in | Opt-in | Always on |
| Top-level `this` | Global object (`window`) | `module.exports` | `undefined` |
| How the top-level scope is built | Global scope | Hidden function wrapper | Module environment |
| Imports | None | `require()` returns a copied value at call time | Live, read-only bindings |
| Top-level `await` | No | No | Yes |
One detail in the first column trips people up. In a classic script, a top-level let does not become a globalThis property, but other classic scripts on the same page can still see it. Scripts share one global lexical scope. Two scripts that both declare let user at the top level cause a SyntaxError in whichever loads second. Modules never collide like this.
Imports Are Live Bindings
An import does not copy a value. It creates a binding that points at the exporting module's variable. When the exporter changes the variable, every importer sees the new value.
// 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
try {
count = 10;
} catch (e) {
console.log(e.name); // "TypeError"
}Run node main.mjs. count in main.mjs behaves like a window onto counter.mjs's module scope. You can read it, but you cannot assign to it from the importing side. The binding is read-only there, and strict mode turns the assignment into a TypeError. Only code inside counter.mjs can change it.
This is the same idea as closures. A closure keeps access to a variable, not a snapshot of its value, and an import keeps access to another module's variable in the same way.
Each Module Is Evaluated Once
A module's top-level code runs the first time any file imports it. Later imports of the same module, from any file, get the same module instance and the same module scope. This makes module-scoped variables a simple way to hold shared state.
// store.mjs
console.log("store.mjs evaluated");
const items = [];
export function add(item) {
items.push(item);
}
export function size() {
return items.length;
}// writer.mjs
import { add } from "./store.mjs";
add("apple");
add("pear");// app.mjs
import "./writer.mjs";
import { size } from "./store.mjs";
console.log(size()); // 2Running node app.mjs prints store.mjs evaluated once, then 2. The items array is private to store.mjs, because nothing exports it. Other modules can only change it through add. This is the closure-based privacy pattern applied at file level.
Hoisting in Modules
Modules use the same creation and execution phases you saw for functions and scripts, but loading happens in more steps. First the engine parses every module in the import graph. Then it links them: it creates each module's scope and connects every import binding to its export. Only after that does it evaluate module bodies, dependencies first.
During linking:
importdeclarations are fully hoisted. They are wired up before any code runs, wherever they appear in the file.- Function declarations are created with their bodies, just as in function scope.
varbindings are created and set toundefined.let,const, andclassbindings are created but left uninitialized, so they are in the TDZ.
Because imports are hoisted, this works:
// math.mjs
export function add(a, b) {
return a + b;
}// use-math.mjs
console.log(add(2, 3)); // 5
import { add } from "./math.mjs";math.mjs was linked and evaluated before the first line of use-math.mjs ran. Place imports at the top anyway. Readers expect them there, and linters enforce it.
The TDZ Across Module Boundaries
Because let and const exports start in the TDZ, circular imports can expose them before they are initialized. Here are two modules that import each other.
// a.mjs
import { b, describeB } from "./b.mjs";
export const a = "A";
export function helperA() {
return "helperA works";
}
console.log("a.mjs sees", b);
console.log(describeB());// b.mjs
import { a, helperA } from "./a.mjs";
export const b = "B";
export function describeB() {
return "b.mjs now sees " + a;
}
console.log(helperA());
try {
console.log(a);
} catch (e) {
console.log("b.mjs:", e.name);
}Run node a.mjs. The output is:
helperA works
b.mjs: ReferenceError
a.mjs sees B
b.mjs now sees AHere is why. a.mjs is the entry point, but it depends on b.mjs, so b.mjs is evaluated first. At that moment a.mjs has been linked but none of its body has run. helperA is a function declaration, so it was initialized during linking and works. a is a const that is still in its TDZ, so reading it throws. After b.mjs finishes, a.mjs runs, initializes a, and logs. The later call to describeB() sees "A", because the import binding is live.
The fixes are the same as for any TDZ problem:
- Remove the cycle by moving shared code into a third module that both import.
- If you must keep the cycle, read the other module's
let/constexports only inside functions that are called later, not at the top level. - Export function declarations for code that must be callable during a cycle, since they are initialized at link time.
Gotchas Checklist
- A top-level
varin a module is not a global. Code that expectswindow.myVarbreaks after conversion. - Top-level
thisisundefined. UseglobalThis. - An imported binding cannot be assigned to, but an imported object can still be mutated.
- Module state is shared by every importer, because each module is evaluated once.
- Circular imports can throw
ReferenceErrorforlet,const, andclassexports in their TDZ. - Browser modules are deferred by default, so they run after the HTML is parsed. Inline classic scripts that expect a module's values to exist may run too early.
Exercise
A classic script contains var theme = "dark"; and another classic script on the same page reads window.theme. You convert the first file to an ES module without changing its code. What does the second script now read, and what are two ways to fix it?
Show answer
It reads undefined, because a top-level var in a module belongs to the module scope and does not create a property on the global object. One fix is to export theme and import it in the second file, after converting that file to a module as well. The other is to assign the global on purpose with globalThis.theme = "dark";, which gives up module isolation for that value.
Exercise
config.mjs contains export let mode = "dev"; export function setMode(m) { mode = m; }. app.mjs imports mode and setMode, calls setMode("prod"), logs mode, and then runs mode = "test";. What is logged, and what happens on the last line?
Show answer
It logs "prod", because imports are live bindings to the exporting module's variable. The assignment mode = "test" throws a TypeError, because imported bindings are read-only in the importing module, and modules always run in strict mode.
Exercise
In a circular import, b.mjs is evaluated before a.mjs and calls an imported a.mjs export at its top level. The call works when a.mjs defines it as export function load() {} but throws when a.mjs defines it as export const load = () => {};. Explain the difference and name the error.
Show answer
During linking, function declarations are created and initialized with their bodies, so load can be called before a.mjs's body runs. A const binding is created but left uninitialized until its declaration line runs, so while b.mjs is evaluating, load is in the temporal dead zone and reading it throws a ReferenceError.