JavaScript ยท Chapter 46 of 55

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.

Example 1 (javascript)
// math.js
export function add(a, b) {
  return a + b;
}

This file exports a named function called add.

Example 2 (javascript)
// app.js
import { add } from "./math.js";
console.log(add(2, 3));
Output
5

app.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.
๐Ÿ’ก Note: A file can have multiple named exports but only one default export.

๐Ÿ“ Quick Quiz

1. Which keyword exposes a value from a module?

2. How many default exports can a module have?

3. What script attribute enables ES modules in browsers?