Lesson 22 of 28

In progress

Course progress

JavaScript

Modules: sharing code between files

Split code into files with import and export, load scripts as modules, and avoid the circular dependency trap.

A single script file becomes unmanageable at a few hundred lines. Modules give each file its own scope and an explicit list of what it shares, which is the difference between a project and a pile of globals.

What you will learn

  • Export and import named and default values.
  • Load a module from HTML and understand what changes.
  • Avoid circular imports and hidden side effects.

Named exports

// money.js
export function toPaise(rupees) {
return Math.round(rupees * 100);
}
export function formatPaise(paise) {
return `₹${(paise / 100).toFixed(2)}`;
}
export const CURRENCY = "INR";
// app.js
import { toPaise, formatPaise } from "./money.js";
console.log(formatPaise(toPaise(249.5)));

Named exports are the default choice: the import names exactly what it uses, and a typo is an error rather than undefined. You can rename on import with as, which helps when two modules export the same name.

Default exports

// storage.js
export default function load(key) {
return JSON.parse(localStorage.getItem(key) ?? "null");
}
import load from "./storage.js";

A module can have one default export. The importer chooses the name, which is convenient and less discoverable: import load from and import getData from both work, so searching the codebase is harder. Prefer named exports for shared utilities and reserve default exports for a module’s single main thing.

You can mix both, but a file that exports a default plus six named values is usually two modules.

Loading a module

<script type="module" src="./app.js"></script>

type="module" changes several behaviours at once:

  • The file is deferred automatically, so the DOM is parsed before it runs.
  • It has its own top-level scope; variables are not global.
  • Strict mode is on.
  • Imports must include a path and extension in the browser (./money.js, not money).
  • It can use top-level await.

Module scripts are fetched with CORS rules, so opening the page with file:// fails. Serve the folder over HTTP, which is the same requirement as fetch.

Dynamic import

import() returns a promise and loads a module on demand. It is useful for a heavy feature that most visitors never use.

async function openEditor() {
const { createEditor } = await import("./editor.js");
return createEditor();
}

The browser fetches the file only when the function runs. That is a real performance tool, not just syntax, and it is how large applications keep the initial bundle small.

The same idea, demonstrated without separate files, is a namespace object that keeps its internals private:

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

money.rate is undefined because the closure keeps it private, which is what module scope gives every file for free.

Side effects and boundaries

A module that runs code on import, such as attaching a listener or writing to storage, has a side effect. That is sometimes intended, and it makes the module hard to test and its import order matter.

Prefer modules that export functions and do nothing until called, because an import that mutates global state makes the order of imports part of your program’s behaviour. If a module must initialise, export an explicit init() and call it from one place.

Circular imports happen when A imports B and B imports A. One of them receives a partially initialised module, and the resulting error mentions a binding that is not defined. The fix is structural: move the shared value into a third module that both import, or pass the dependency as a parameter.

A module imported in two places runs once, not twice, which is usually what you want. But if that module has a side effect, the effect still happens on the first import, at a time determined by the import graph rather than by your code. Keep modules side-effect free and the ordering question disappears.

Sketch three files: math.js exporting add and multiply, format.js exporting formatTotal, and app.js importing both and logging a formatted total. Write the import lines exactly as the browser needs them.

Show solution
// math.js export const add = (a, b) => a + b; export const multiply = (a, b) => a * b; // format.js export function formatTotal(value) { return `Total: ${value.toFixed(2)}`; } // app.js import { add, multiply } from "./math.js"; import { formatTotal } from "./format.js"; console.log(formatTotal(multiply(add(2, 3), 4)));

Each import names the file with its extension and a relative path. The app composes the other two without either knowing about the other.

Recap

  • Named exports make dependencies explicit; a default export is for a module’s single main value.
  • type="module" gives deferred execution, strict mode, file scope and top-level await.
  • Avoid side effects and circular imports; move shared code into its own module.

Next, you will model state and behaviour with classes, including private fields.

Do modules need a bundler?
No. Browsers support modules directly. A bundler helps with older browsers and many small files, not with correctness.
Why does my import fail with a 404?
The path is resolved relative to the importing file, and browsers require the extension. Check the Network panel for the exact URL requested.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.