JavaScript Modules
Modules let you split code across multiple files, each exporting specific functions, objects, or values that other files can import. This promotes organization and code reuse.
Modern JavaScript uses ES module syntax: `export` to expose values from a file, and `import` to bring them into another file, using `<script type="module">` in the browser.
Exporting
`export function add(a, b) { return a + b; }` (named export) or `export default function() {...}` (default export, one per file).
Importing
`import { add } from './math.js';` imports a named export. `import myFunc from './file.js';` imports a default export.
// math.js
export function add(a, b) {
return a + b;
}This file exports a named function called add.
// app.js
import { add } from "./math.js";
console.log(add(2, 3));5app.js imports and uses the add function from math.js.
Key points
- export exposes functions/values from a file; import brings them in.
- Named exports use curly braces on import; default exports don't.
- Modules require `type="module"` in a script tag when used in browsers.
- Modules help organize large codebases into maintainable pieces.
