JavaScript Named and Default Exports
A named export is shared under its own name. A default export is the module's main value, shared without a name.
Pick named exports by name
The module exports add and subtract by name. The main script reads each one through its name.
(async () => {
const url = URL.createObjectURL(new Blob(["export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;"], { type: "text/javascript" }));
const math = await import(url);
console.log(math.add(10, 4));
console.log(math.subtract(10, 4));
})();Read the default export
The module exports one main value. The loaded module holds it under the word default.
(async () => {
const url = URL.createObjectURL(new Blob(["export default 'Main value';"], { type: "text/javascript" }));
const module = await import(url);
console.log(module.default);
})();Named and default exports live together
One module can hold both kinds at once. name is read by its own name, and role is read through default.
(async () => {
const url = URL.createObjectURL(new Blob(["export const name = 'Ada'; export default { role: 'Teacher' };"], { type: "text/javascript" }));
const module = await import(url);
console.log(module.name);
console.log(module.default.role);
})();Example
(async () => {
const url = URL.createObjectURL(new Blob(["export const double = (n) => n * 2; export default (n) => n * n;"], { type: "text/javascript" }));
const math = await import(url);
console.log(math.double(5));
console.log(math.default(5));
})();Key points
- Named export: a value a module shares under its own name
- Default export: the one main value a module shares, without a name
- A module can have many named exports and only one default export.
- A named import must use the exact name from the export.
- A default import can use any name, because the value has no name of its own.
- The static import and export lines are shown in the table, not run here.
In this example, the module exports double by name and a squaring function as its default. The main script reads the named export through its name. It reads the default export through the word default.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Static import and export forms
| Statement | What it does |
|---|---|
| export const pi = 3.14; | Shares pi under its own name |
| export function add(a, b) { return a + b; } | Shares add under its own name |
| export default 42; | Shares 42 as the main value |
| export default function greet() { return 'Hi'; } | Shares greet as the main value |
| import { pi } from './math.js'; | Loads pi by its name |
| import answer from './math.js'; | Loads the main value as answer |
Exercise
How many default exports can one module have?