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.
