ES Modules

Updated · 9 min read
hardES2026javascriptmodulesimportexportinterview

An ES module is a JavaScript file that has its own private scope and shares code with other files only through export and import. Modules are how real applications are organized: one file for money formatting, one for the fee rules, one for the user interface, each importing exactly what it needs. Standardized in ES2015, modules now work natively in every browser and in Node.js, replacing older patterns such as global variables, IIFEs and CommonJS require.

In One Minute

  • Each module file has its own scope: top-level variables are private unless exported.
  • Named exports: export function format() {}, imported with import { format } from "./money.js".
  • Default export: export default class Tracker {}, imported with any name: import Tracker from "./tracker.js".
  • import * as money from "./money.js" imports everything as a namespace object.
  • Modules are strict, run once, are deferred in browsers, and support top-level await.

Exporting and Importing

Named Exports

A module exports values by name; another module imports them by the same names, in braces:

money.js▶ Try it
export const CURRENCY = "USD";
 
export function toCents(dollars) {
  return Math.round(dollars * 100);
}
 
export function formatCents(cents) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: CURRENCY }).format(cents / 100);
}
 
const internalHelper = () => "not exported";
Output
 
app.js▶ Try it
import { toCents, formatCents, CURRENCY } from "./money.mjs";
 
const fees = [120, 85.5, 45];
const total = fees.map(toCents).reduce((a, b) => a + b, 0);
console.log(formatCents(total), CURRENCY);
console.log(typeof internalHelper);
Output
$250.50 USD
undefined

Explanation: money.js exports three names; app.js imports them. internalHelper isn't exported, so it is invisible outside its module, even though it's at the top level. (This site's checker saves module examples with an .mjs extension, which is why the import says ./money.mjs; in your own project, you'd import ./money.js.)

Export Styles

SyntaxMeaning
export const x = 1; export function f() {} export class C {}Export a declaration
export { a, b };Export existing names (often at the end of the file)
export { a as alias };Export under a different name
export default value;The module's default export (one per module)
export { x } from "./other.js";Re-export from another module
export * from "./other.js";Re-export all named exports

Import Styles

SyntaxMeaning
import { a, b } from "./m.js";Named imports
import { a as alias } from "./m.js";Rename on import
import Default from "./m.js";The default export, under any name
import Default, { a } from "./m.js";Both
import * as ns from "./m.js";Everything, as a namespace object
import "./m.js";Run the module for its side effects only

Default Exports

A module can have one default export, typically its main class or function. The importer chooses the name:

tracker.js▶ Try it
export default class FeeTracker {
  #payments = [];
  add(amount) { this.#payments.push(amount); return this; }
  get total() { return this.#payments.reduce((a, b) => a + b, 0); }
}
 
export const VERSION = "2.1.0";
Output
 
use-tracker.js▶ Try it
import Tracker, { VERSION } from "./tracker.mjs";
import * as trackerModule from "./tracker.mjs";
 
console.log(new Tracker().add(120).add(85).total, VERSION);
console.log(Object.keys(trackerModule).sort());
console.log(trackerModule.default === Tracker);
Output
205 2.1.0
[ 'VERSION', 'default' ]
true

A namespace import shows that a default export is simply an export named default.

Renaming and Namespaces

rename.js▶ Try it
import { formatCents as usd, toCents } from "./money.mjs";
import * as money from "./money.mjs";
 
console.log(usd(toCents(19.99)));
console.log(money.formatCents(money.toCents(45)));
try {
  money.CURRENCY = "EUR";
} catch (err) {
  console.log(err.name, "| still", money.CURRENCY, "| frozen?", Object.isFrozen(money));
}
Output
$19.99
$45.00
TypeError | still USD | frozen? false

Renaming avoids clashes between modules that export the same name. A namespace object is read-only from outside: assigning to it throws (modules are strict). Interestingly, Object.isFrozen reports false, because its properties must stay live: the exporting module can still change them, as the next section shows.

Live Bindings

An import is not a copy: it's a live, read-only view of the exported variable. If the exporting module changes the variable, importers see the new value; importers can't assign to it:

counter.js▶ Try it
export let receiptCount = 0;
export function nextReceipt() {
  receiptCount++;
  return `R-${1000 + receiptCount}`;
}
Output
 
live.js▶ Try it
import { receiptCount, nextReceipt } from "./counter.mjs";
 
console.log(receiptCount);
nextReceipt();
nextReceipt();
console.log(receiptCount);
 
try {
  receiptCount = 99;
} catch (err) {
  console.log(err.name + ": " + err.message);
}
Output
0
2
TypeError: Assignment to constant variable.

How Modules Behave

BehaviorDetail
Own scopeTop-level declarations are private to the file
Strict modeAlways, without "use strict"
Run onceImporting the same module from many files runs it once; all share one instance
Imports are hoistedimport statements are processed before the module's code runs, wherever they appear
Static structureimport/export must be at the top level, with string literal paths, so tools can analyze them
Top-level awaitAllowed; modules that import it wait
this at the top levelundefined
import.metaInformation about the current module, such as import.meta.url

Because a module runs once and is shared, it's a natural place for state shared across an app (a settings object, a cache): every importer gets the same instance.

Modules in the Browser

Load a module with type="module". Modules are deferred automatically (they run after the HTML is parsed) and import other files by relative or absolute URL:

index.html
<script type="module" src="/js/app.js"></script>
 
<script type="module">
  import { formatCents } from "/js/money.js";
  document.querySelector("#total").textContent = formatCents(25050);
</script>
RuleWhy
Paths need ./, ../, / or a full URLA bare name like "money" isn't a URL (import maps can map bare names; next lesson)
Include the file extensionThe browser doesn't guess .js
Serve over HTTP, not file://Modules are fetched with CORS rules; opening the file directly fails
Cross-origin modules need CORS headersSame as fetch
module-page.html
<p id="total"></p>
<script type="module">
  const money = await import("data:text/javascript," + encodeURIComponent(
    'export const formatCents = (c) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(c / 100);'
  ));
  document.querySelector("#total").textContent = money.formatCents(25050);
  console.log(document.querySelector("#total").textContent);
  console.log("top-level this:", this);
</script>
Output
$250.50
top-level this: undefined

(The checker serves one HTML page, so this example builds a module from a data: URL; in a real site you'd import from a .js file.)

Modules in Node.js

Node.js supports two module systems: ES modules (this lesson) and the older CommonJS (require and module.exports). A file is treated as an ES module when:

  • its name ends in .mjs, or
  • it ends in .js and the nearest package.json has "type": "module".
package.json
{
  "name": "fee-tracker",
  "type": "module"
}

Built-in Node.js modules are imported with the node: prefix: import { readFile } from "node:fs/promises";. The dynamic imports lesson covers CommonJS and how the two systems interoperate.

In Practice

The Fee Tracker split into modules: a pure rules module, a formatting module, and an entry module that wires them together. Each can be tested and changed on its own:

rules.js▶ Try it
export const GRACE_DAYS = 10;
export function lateFee(daysLate, { rate = 2, cap = 30 } = {}) {
  return Math.min(Math.max(daysLate - GRACE_DAYS, 0) * rate, cap);
}
export function balance(fee, payments) {
  return fee - payments.reduce((a, b) => a + b, 0);
}
Output
 
main.js▶ Try it
import { lateFee, balance } from "./rules.mjs";
import { formatCents, toCents } from "./money.mjs";
 
const student = { name: "Srihitha", fee: 450, payments: [200, 150], daysLate: 16 };
const due = balance(student.fee, student.payments) + lateFee(student.daysLate);
console.log(`${student.name}: ${formatCents(toCents(due))} due`);
Output
Srihitha: $112.00 due

Common Mistakes

Missing the extension or ./ in browser imports. import "money" fails. Write import "./money.js".

Opening module pages from file://. Browsers block them. Use a local server.

Expecting import to copy values. Imports are live views of the exporter's variables.

Assigning to an import. Imports are read-only: TypeError.

Interview Corner

What is the difference between named and default exports?

A module can have many named exports, imported by their exact names in braces (renamable with as), and at most one default export, imported without braces under any name. A default export is just an export named default. Named exports are friendlier to tooling and refactoring.

How do ES modules differ from scripts?

Modules have their own top-level scope (no implicit globals), are always strict, are evaluated once and shared, have hoisted static imports, support top-level await, have this === undefined at the top level, are deferred in browsers, and are fetched with CORS.

Practice

Challenge: Create a module validators.js with named exports isZip(text) and isPhone(text), then import both under a namespace and test them.

Show solution
validators.js▶ Try it
export const isZip = (text) => /^\d{5}(-\d{4})?$/.test(text);
export const isPhone = (text) => /^\(?\d{3}\)?[\s.-]?\d{3}[-.]?\d{4}$/.test(text);
Output
 
Show solution
check.js▶ Try it
import * as validate from "./validators.mjs";
 
console.log(validate.isZip("75201"), validate.isZip("7520"));
console.log(validate.isPhone("(214) 555-0100"), validate.isPhone("555-0100"));
Output
true false
true false

Quick check: ES modules

3 questions
1How many default exports can a module have?
2Is a top-level const in a module visible to other modules?
3What makes a .js file an ES module in Node.js?

Key Takeaways

TaskCode
Named exportexport function format() {}
Named importimport { format } from "./money.js"
Default export / importexport default class X {} / import X from "./x.js"
Renameimport { format as usd } from "./money.js"
Namespaceimport * as money from "./money.js"
Re-exportexport { format } from "./money.js"

Was this tutorial helpful?

Lesson 111 of 139