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.
ES6 Modules (import / export) allow you to split JavaScript code into separate, reusable files with strict scope boundaries.
Modules prevent global scope pollution, clarify explicit file dependencies, and enable modern bundlers (Vite, Next.js) to tree-shake unused code.
{ func }.// 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
Modules can aggregate utilities into clean entry points:
// index.js
export { add, subtract } from "./mathUtils.js";
import add from './mathUtils.js') attempts to load the default export, resulting in undefined or import errors!./ or ../ relative paths (import { add } from "./mathUtils.js"). Omiting ./ causes Node to look inside node_modules.Write it yourself. The tests below run against your code.
Use named exports for utility libraries. Next, let's explore JavaScript Proxy 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.
`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.
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.