Thuta Learning
JavaScript
AdvancedProgrammingBeginner

JS Modules

JavaScriptLesson 4430 min

What you'll walk away with

  • Write named and default exports and import each with the matching syntax
  • Explain module scope, strict mode and why a module runs only once
  • Describe live bindings and why an imported name cannot be reassigned
  • Run modules in the browser with type="module" and in Node with .mjs or "type": "module"
  • Split logic, UI and startup into separate modules with one-way dependencies

Explain it simply

Explain it simply

Think of a module as a room with the door closed. Inside, you can keep your things (variables and functions) however you like, and nobody outside can see them. Anything you want to offer other rooms goes out through a window called export.

When a room needs something from another room, it asks by name with import: "from that room, I want this". So the top of any file tells you exactly what it uses and where it comes from, and two files can no longer collide just because they picked the same variable name.

Problem → Why → Solution

The problem: colliding globals

Before modules, websites loaded JavaScript with plain <script> tags in a fixed order. Every file's top-level var declarations and functions landed in one shared global scope. If both utils.js and cart.js defined a function called format, whichever loaded last silently replaced the other.

Nothing in the code said which file needed which. Someone reorders the <script> tags, and suddenly you get "format is not defined" or prices shown in the wrong currency, with no hint of where the problem came from.

three-plain-scripts.js
// utils.js  (loaded first with a plain <script>)
function format(n) { return "$" + n.toFixed(2); }
var total = 0;

// cart.js   (loaded second)
var total = 0;                              // the SAME global as in utils.js
function format(n) { return n + " MMK"; }   // silently replaces utils' format

// app.js    (loaded last)
console.log(format(5)); // "5 MMK" - the winner depends on <script> order

Why does this happen?

Plain scripts have no file boundaries. The whole page shares one global namespace, so equal names collide, and dependencies hide inside the order of the script tags. In an ES module each file gets its own scope and every dependency is written out in an import line, which removes both problems.

Core concept: export, import and the life of a module

1. One file, one scope

Top-level const, let and function declarations in a module are not globals; anything you do not export is private. Modules always run in strict mode, and top-level this is undefined.

2. Export: named and default

A module can have as many named exports as it likes, such as export const TAX = 0.07 or export function total(). It can have at most one export default, which stands for the module's main value.

3. Import is static and runs first

Named exports are imported with their exact names in braces, { total }, and can be renamed with as. A default export is imported without braces under any name you choose. import statements must sit at the top level with a string-literal path, and they are resolved and loaded before the file's code runs.

4. Runs once, shares live bindings

Even if ten files import a module, its code runs once and the result is cached. An imported name is not a copy of the value; it is a live binding wired to the exporter's variable. When the exporter changes the value, importers see the change, but an importer is not allowed to assign to it.

5. Dynamic import()

For a module you only want when it is needed, call import("./chart.js") like a function. It returns a promise for the module's namespace object, and inside a module you can await it at the top level.

Named exportDefault export
Per moduleAs many as you likeAt most one
Import syntaximport { total } from ...import anyName from ...
NameFixed by exporter (rename with as)Chosen by the importer
Mental model: closed rooms with windows
  1. Each file is a closed room
  2. export shows a thing in the window
  3. import asks for it by name
  4. Each room is built only once

An imported value is something you watch through the window: you see it when the owner changes it, but you cannot reach in and change it yourself.

General pattern

javascript
// some-module.js
export const someValue = 1;
export function someHelper() { /* ... */ }
export default function mainThing() { /* ... */ }

// another-module.js
import mainThing, { someValue, someHelper as helper } from "./some-module.js";
import * as everything from "./some-module.js";

const lazy = await import("./rarely-used.js"); // dynamic import

Import the default without braces and named exports inside { }. * as gathers every export into one object, and import() loads a module on demand. Relative paths start with ./ and include the .js extension.

Run the module features in a single file

So that you can run it in Node without creating several files, this example imports Node's built-in modules (node:path and node:util) and also exports two things of its own. Save it as main.mjs and run node main.mjs; the .mjs extension makes Node treat it as an ES module.

main.mjs
// main.mjs - the .mjs extension tells Node this file is an ES module
import { basename, extname } from "node:path"; // named imports
import * as path from "node:path"; // namespace import: every export in one object

// Things this file offers to other modules
export const TAX_RATE = 0.07;
export function priceWithTax(price) {
  return Math.round(price * (1 + TAX_RATE) * 100) / 100;
}

// Module scope: a top-level const does not become a global
const secret = "visible only in this file";
console.log(typeof secret, typeof globalThis.secret);

// Modules always run in strict mode: top-level `this` is undefined
console.log(this);

console.log(basename("/src/utils/math.js"), extname("app.mjs"));
console.log(path.basename === basename);

// Imported bindings are read-only for the importer
try {
  basename = () => "hacked";
} catch (err) {
  console.log(err.name);
}

// Dynamic import(): load a module later; it returns a promise
const { format } = await import("node:util");
console.log(format("%s items cost %d", 3, priceWithTax(19.99)));

Code breakdown

  1. Named importsimport { basename, extname } from "node:path"; // named imports

    Takes two named exports from node:path by their exact names. These lines are processed before any other code in the file runs.

  2. Exportsexport const TAX_RATE = 0.07;

    Another file could write import { TAX_RATE, priceWithTax } from "./main.mjs". secret is not exported, so no other file can reach it.

  3. No global leakconsole.log(typeof secret, typeof globalThis.secret);

    secret is a string inside this file but does not exist on the global object, so the line prints "string undefined".

  4. Same function, two routesconsole.log(path.basename === basename);

    The namespace import and the named import point at the same export of the same module, so this is true: the module was loaded only once.

  5. Read-only bindingbasename = () => "hacked";

    Assigning to an imported name throws a TypeError: an importer can never overwrite another module's export.

  6. Dynamic importconst { format } = await import("node:util");

    import() returns a promise, so top-level await waits for it and the namespace object is destructured. format then fills in the %s and %d placeholders.

You should see
string undefined
undefined
math.js .mjs
true
TypeError
3 items cost 21.39

Splitting a project into modules

Real apps split files by responsibility. In the layout below, main.js handles startup and the DOM, cart.js holds state and rules, and format.js holds pure helpers that never touch the DOM. The arrows point one way only, and format.js imports nothing, which makes it the easiest file to test in Node.

text
One-way dependencies
--------------------
index.html
   |  <script type="module" src="./main.js">
   v
main.js  --imports-->  cart.js  --imports-->  format.js
(startup + DOM)        (state + rules)        (pure helpers)

Rule: arrows never point back. If cart.js and format.js both
need something, move it into a new module both can import.
index.html
<!-- type="module" makes main.js a module; it is deferred automatically -->
<script type="module" src="./main.js"></script>

<!-- inside main.js -->
<!-- import { addItem, total } from "./cart.js";   ./ and .js are required -->

Browsers need a server for modules

Open index.html by double-clicking (file://) and most browsers block module scripts under their CORS rules; serve the folder with a local server such as npx serve or VS Code's Live Server. Browsers also do not understand bare package names like "lodash" on their own, so you need a bundler such as Vite or an import map. In Node, use the .mjs extension or add "type": "module" to package.json.

In real projects

In real projects

Almost every JavaScript project today is organised as modules. Folders such as src/api/, src/ui/ and src/utils/ hold files that each own one job and export only what others need. Bundlers such as Vite, webpack and esbuild follow the import lines to package the code for the browser, and they drop named exports that nothing uses, which is called tree-shaking.

On large pages, heavy code such as a chart library is loaded with import() only when the user opens the chart tab. This code splitting keeps the first page load fast.

Modules also make testing easier. In the next two project lessons, the calculator and the todo list keep their logic in DOM-free modules that a test runner like node --test can check without opening a browser, while a separate module imports that logic and only handles the display. Many npm packages now ship as ES modules, though you will still meet CommonJS (require and module.exports) in older Node projects.

Common mistakes

Common mistakes

Mixing up default and named imports

If cart.js only has export function total(), then import total from "./cart.js" fails with a SyntaxError saying it "does not provide an export named 'default'". Named exports need { total }; only a default export is imported without braces.

Leaving out ./ or .js in the path

Browsers and Node's ES module loader do not guess extensions, so import "./utils" gives a module-not-found error, and import "utils.js" without ./ is treated as a package name. Write the full "./utils.js".

Two modules importing each other

When a.js imports b.js and b.js imports a.js, one of them runs while the other's const values are not initialised yet, which often ends in "Cannot access 'X' before initialization". Move whatever both need into a third module.

Trying to change an import like a variable

After import { count } from "./counter.js", writing count++ throws a TypeError. To change the value, the exporting module has to export a function such as increment() that does it.

Mini challenge

A cart module with private state

Write a module called cart.mjs. Keep the item list private (not exported), export named functions to add items and compute the total, and make a summary function the default export. Also write how main.mjs would import them.

  • Do not export the items array
  • Export FREE_SHIPPING_FROM (50), addItem(name, price, qty = 1) and total() as named exports
  • addItem throws a RangeError for a negative price or a qty below 1
  • summary() is the default export: shipping is 0 from a total of 50, otherwise 5
  • The demo section runs only when the file is executed directly
cart.mjs
// ---- cart.mjs ----
import { pathToFileURL } from "node:url";

// TODO: a private array of { name, price, qty } - do NOT export it

// TODO: export FREE_SHIPPING_FROM = 50

// TODO: export addItem(name, price, qty = 1); throw RangeError on bad input

// TODO: export total() - sum of price * qty

// TODO: export default summary() -> "N line(s), total X.XX, shipping S"

// Demo: true only when you run "node cart.mjs" directly
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
  // TODO: add a few items, print summary(), and show the RangeError message
}

// ---- main.mjs (another file) ----
// TODO: import summary (default) plus addItem and total (named) from "./cart.mjs"

Expected: Running node cart.mjs prints 2 line(s), total 31.00, shipping 5, then 3 line(s), total 61.00, shipping 0, then Invalid item: Broken.

Show hint

You can write export default function summary() { ... }. In main.mjs, put the default first and the named exports in braces: import summary, { addItem, total } from "./cart.mjs".

Show solution
cart.mjs
// ---- cart.mjs ----
import { pathToFileURL } from "node:url";

const items = []; // private: no other module can reach this array

export const FREE_SHIPPING_FROM = 50;

export function addItem(name, price, qty = 1) {
  if (price < 0 || qty < 1) throw new RangeError(`Invalid item: ${name}`);
  items.push({ name, price, qty });
}

export function total() {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

export default function summary() {
  const shipping = total() >= FREE_SHIPPING_FROM ? 0 : 5;
  return `${items.length} line(s), total ${total().toFixed(2)}, shipping ${shipping}`;
}

// Demo: runs for "node cart.mjs", not when another module imports this file
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
  addItem("Notebook", 12.5, 2);
  addItem("Pen", 1.2, 5);
  console.log(summary());
  addItem("Backpack", 30);
  console.log(summary());
  try {
    addItem("Broken", -1);
  } catch (err) {
    console.log(err.message);
  }
}

// ---- main.mjs (another file) ----
// import summary, { addItem, total } from "./cart.mjs";
// addItem("Mug", 8);
// console.log(summary(), total());

Quick quiz 1 / 3

cart.js contains export default function total() {} and export const TAX = 0.07;. Which import is correct?

Quick quiz 2 / 3

counter.js has export let count = 0; export function inc() { count++; }. main.js runs import { count, inc } from "./counter.js"; inc(); console.log(count);. What is printed?

Quick quiz 3 / 3

logger.js has console.log("logger ready") at its top level. Both a.js and b.js import logger.js, and main.js imports a.js and b.js. How many times is "logger ready" printed?

What to remember

  • Each module has its own scope; whatever you do not export stays private
  • Import named exports with { name } and a default export without braces
  • A module runs once, and its imports are read-only live bindings
  • Browsers need type="module" and a server; Node needs .mjs or "type": "module"
  • Keep dependencies one-way and put logic in DOM-free modules

MDN — JavaScript Modules — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS Modules | Thuta Learning