JavaScript ES6 modules allow us to export and import code between files. There are two main types of exports:
1ī¸âŖ Named Exports (export)
2ī¸âŖ Default Exports (export default)
Table of Contents
đš 1. Named Export (export)
- Allows exporting multiple values from a module.
- Must use the exact names when importing.
- Can be imported using
{}(destructuring).
đ¸ Example of Named Export
đ math.js
export const PI = 3.14159;
export function square(x) {
return x * x;
}đ main.js (Importing Named Exports)
import { PI, square } from './math.js';
console.log(PI); // â
3.14159
console.log(square(4)); // â
16â
Can export multiple values
â Must use exact names when importing
đš 2. Default Export (export default)
- Exports a single value from a module.
- Can be imported with any name (no
{}needed).
đ¸ Example of Default Export
đ math.js
export default function cube(x) {
return x * x * x;
}đ main.js (Importing Default Export)
import myCube from './math.js'; console.log(myCube(3)); // â 27
â
Can be imported with any name
â Only one default export per file
đš 3. Named Export + Default Export (Together)
export const add = (a, b) => a + b;
export default function multiply(a, b) {
return a * b;
}Import Both
import multiply, { add } from './math.js';
console.log(multiply(2, 3)); // â
6
console.log(add(2, 3)); // â
5đš 4. Key Differences (export vs export default)
| Feature | Named Export (export) | Default Export (export default) |
|---|---|---|
| Exports | Multiple per file | Only one per file |
| Import Syntax | {} required (import { x }) | No {} (import x) |
| Import Name | Must match export name | Can be any name |
| Flexibility | More structured | Easier to import |
| Example Import | import { square } from './file.js' | import myFunc from './file.js' |
đ Quick Summary
- Use
exportwhen exporting multiple values. - Use
export defaultfor one main value per module. - You can combine both in the same file.
