๐Ÿš€ 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