Curriculum Series

default vs named export

default vs named export

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.js
2function add(a, b) {
3 return a + b;
4}
5
6export default add;

When you import it, you can give it any name you want:

JAVASCRIPT
1// main.js
2import calculator from './math.js'; // I called it "calculator"
3
4calculator(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.js
2export function add(a, b) {
3 return a + b;
4}
5
6export function subtract(a, b) {
7 return a - b;
8}
9
10export const PI = 3.14159;

When you import named exports, you must use the exact names and put them in curly braces:

JAVASCRIPT
1// main.js
2import { add, subtract, PI } from './math.js';
3
4add(5, 3); // 8
5subtract(10, 4); // 6
6console.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.js
2
3// Named exports
4export function add(a, b) {
5 return a + b;
6}
7
8export function subtract(a, b) {
9 return a - b;
10}
11
12export const PI = 3.14159;
13
14// Default export
15function multiply(a, b) {
16 return a * b;
17}
18
19export default multiply;

Importing from Utils.js

JAVASCRIPT
1// main.js
2import multiply, { add, subtract, PI } from './utils.js';
3// ↑ default ↑ named exports
4
5console.log(multiply(4, 5)); // 20
6console.log(add(2, 3)); // 5
7console.log(subtract(10, 4)); // 6
8console.log(PI); // 3.14159

Finished reading?

Mark this topic as solved to track your progress.