default vs named export

JavaScript React

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.js
function add(a, b) {
return a + b;
}

export default add;

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

// main.js
import calculator from './math.js'; // I called it "calculator"

calculator(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.

// math.js
export 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.js
import { add, subtract, PI } from './math.js';

add(5, 3); // 8
subtract(10, 4); // 6
console.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

// utils.js

// Named exports
export function add(a, b) {
return a + b;
}

export function subtract(a, b) {
return a - b;
}

export const PI = 3.14159;

// Default export
function multiply(a, b) {
return a * b;
}

export default multiply;

Importing from Utils.js

// main.js
import multiply, { add, subtract, PI } from './utils.js';
// ↑ default ↑ named exports

console.log(multiply(4, 5)); // 20
console.log(add(2, 3)); // 5
console.log(subtract(10, 4)); // 6
console.log(PI); // 3.14159
00:00

Table of Contents