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.
JAVASCRIPT
1// math.js2function add(a, b) {3 return a + b;4}56export default add;
When you import it, you can give it any name you want:
JAVASCRIPT
1// main.js2import calculator from './math.js'; // I called it "calculator"34calculator(2, 3); // Works fine
Named 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.
JAVASCRIPT
1// math.js2export function add(a, b) {3 return a + b;4}56export function subtract(a, b) {7 return a - b;8}910export const PI = 3.14159;
When you import named exports, you must use the exact names and put them in curly braces:
JAVASCRIPT
1// main.js2import { add, subtract, PI } from './math.js';34add(5, 3); // 85subtract(10, 4); // 66console.log(PI); // 3.14159
Key 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
JAVASCRIPT
1// utils.js23// Named exports4export function add(a, b) {5 return a + b;6}78export function subtract(a, b) {9 return a - b;10}1112export const PI = 3.14159;1314// Default export15function multiply(a, b) {16 return a * b;17}1819export default multiply;
Importing from Utils.js
JAVASCRIPT
1// main.js2import multiply, { add, subtract, PI } from './utils.js';3// ↑ default ↑ named exports45console.log(multiply(4, 5)); // 206console.log(add(2, 3)); // 57console.log(subtract(10, 4)); // 68console.log(PI); // 3.14159