Course outline · 0% complete

0/27 lessons0%

Course overview →

import and export

lesson 8-3 · ~8 min · 22/27

ES modules in two sentences

Modules exist because the old world was misery: every script file shared one global namespace, so two libraries defining utils silently overwrote each other, and load order was a nightly bug. Modules fix both. A module is a file with its own top-level scope: nothing leaks out unless you export it, and nothing comes in unless you import it. There are two kinds of exports:

// math.js
export const PI = 3.14159;          // named export (many per file)
export function area(r) {
  return PI * r * r;
}
export default function describe() { // default export (one per file)
  return "math helpers";
}
// app.js
import describe, { PI, area as circleArea } from "./math.js";

Named imports use braces and must match the exported names (rename with as). The default import has no braces, and you pick any name for it.

Three facts interviewers probe

  1. Modules run once. The first import executes the file, and every later import reuses the same result. Two files importing the same module share one copy of its state, which makes a module an app-wide singleton (the module pattern from lesson 1-3, built into the language).
  2. Module code is strict mode automatically, so a plain function call has this === undefined, exactly as promised in lesson 2-1.
  3. Named imports are live bindings, connected views of the exported variable, not copies made at import time.

Quiz

counter.js has `export default createCounter`. Which import is correct?

Problem

Fill in the blank with the missing keyword: ```javascript import { formatDate ___ fmt } from "./dates.js"; ``` After this line, the function is used as `fmt(...)`.

Quiz

config.js runs `console.log("loading config")` at its top level. Five different files import it. How many times does that log print?