ES Modules: import & export
Quick Overview
A module's code runs once no matter how many files `import` it, and every importer shares that one instance. Named exports must match by name; a default export can be renamed freely at the import site.
Deep Dive
1. Modular Architecture
ES6 Modules (import / export) allow you to split JavaScript code into separate, reusable files with strict scope boundaries.
2. Why It Matters
Modules prevent global scope pollution, clarify explicit file dependencies, and enable modern bundlers (Vite, Next.js) to tree-shake unused code.
3. Named vs Default Exports
- Named Exports: Export multiple items per file by name. Must be imported using exact matching curly braces
{ func }. - Default Export: Export one primary value per file. Can be imported with any local name without curly braces.
// mathUtils.js (Module File)
export const add = (a, b) => a + b; // Named export
export const subtract = (a, b) => a - b; // Named export
export default function multiply(a, b) { // Default export
return a * b;
}
// app.js (Main File)
import multiply, { add, subtract } from "./mathUtils.js";
console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6
4. Re-exporting Utilities
Modules can aggregate utilities into clean entry points:
// index.js
export { add, subtract } from "./mathUtils.js";
5. Common Mistakes
- Mixing Up Curly Braces: Importing a named export without curly braces (
import add from './mathUtils.js') attempts to load the default export, resulting inundefinedor import errors! - Omitting Relative Paths in Node/Browser: Importing local files requires
./or../relative paths (import { add } from "./mathUtils.js"). Omiting./causes Node to look insidenode_modules.
6. Try It Yourself
Write it yourself. The tests below run against your code.
Calculate Area Utility Summary
Examples
7. Next Steps
Use named exports for utility libraries. Next, let's explore JavaScript Proxy Objects!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.