default vs named export
JavaScriptReact
default vs named export
In JavaScript, there are two main ways to export things from a file so other files can use them they are default export and named export.
Default Export
Think of this as the "main thing" you're sharing from a file. Each file can only have one default export.
// math.jsfunction add(a, b) { return a + b;}export default add;When you import it, you can give it any name you want:
// main.jsimport calculator from './math.js'; // I called it "calculator"calculator(2, 3); // Works fineNamed Export
This is like sharing multiple specific things from a file, each with their own name. You can have many named exports in one file.
// math.jsexport function add(a, b) { return a + b;}export function subtract(a, b) { return a - b;}export const PI = 3.14159;When you import named exports, you must use the exact names and put them in curly braces:
// main.jsimport { add, subtract, PI } from './math.js';add(5, 3); // 8subtract(10, 4); // 6console.log(PI); // 3.14159Key Differences
Default Export:
- One per file
- Import with any name you want
- No curly braces needed
Named Export:
- Multiple per file
- Must import with exact names
- Requires curly braces
You can have both default and named exports in the same file
This is actually a common pattern.
Example Utils.js
// utils.js// Named exportsexport function add(a, b) { return a + b;}export function subtract(a, b) { return a - b;}export const PI = 3.14159;// Default exportfunction multiply(a, b) { return a * b;}export default multiply;Importing from Utils.js
// main.jsimport multiply, { add, subtract, PI } from './utils.js';// ↑ default ↑ named exportsconsole.log(multiply(4, 5)); // 20console.log(add(2, 3)); // 5console.log(subtract(10, 4)); // 6console.log(PI); // 3.14159