🚀 export vs export default in JavaScript Modules

JavaScript ES6 modules allow us to export and import code between files. There are two main types of exports:

1️⃣ Named Exports (export)
2️⃣ Default Exports (export default)


🔹 1. Named Export (export)

  • Allows exporting multiple values from a module.
  • Must use the exact names when importing.
  • Can be imported using {} (destructuring).

🔸 Example of Named Export

📂 math.js

export const PI = 3.14159;
export function square(x) {
    return x * x;
}

📂 main.js (Importing Named Exports)

import { PI, square } from './math.js';

console.log(PI);         // ✅ 3.14159
console.log(square(4));  // ✅ 16

Can export multiple values
Must use exact names when importing


🔹 2. Default Export (export default)

  • Exports a single value from a module.
  • Can be imported with any name (no {} needed).

🔸 Example of Default Export

📂 math.js

export default function cube(x) {
    return x * x * x;
}

📂 main.js (Importing Default Export)

import myCube from './math.js';

console.log(myCube(3));  // ✅ 27

Can be imported with any name
Only one default export per file


🔹 3. Named Export + Default Export (Together)

export const add = (a, b) => a + b;
export default function multiply(a, b) {
    return a * b;
}

Import Both

import multiply, { add } from './math.js';

console.log(multiply(2, 3)); // ✅ 6
console.log(add(2, 3));      // ✅ 5

🔹 4. Key Differences (export vs export default)

FeatureNamed Export (export)Default Export (export default)
ExportsMultiple per fileOnly one per file
Import Syntax{} required (import { x })No {} (import x)
Import NameMust match export nameCan be any name
FlexibilityMore structuredEasier to import
Example Importimport { square } from './file.js'import myFunc from './file.js'

🚀 Quick Summary

  • Use export when exporting multiple values.
  • Use export default for one main value per module.
  • You can combine both in the same file.

Leave a Reply