Question 38

Question

Explain how to use named exports and default exports together in a single module.

Answer

Named exports and default exports are both powerful features of ES6 modules, allowing for organized and flexible code sharing.

Here's how you can use them together in a single module:

// myModule.js

export function greet(name) {
  return `Hello, ${name}!`;
}

export const PI = 3.14159; // Named export - constant

export default function add(a, b) { 
  return a + b;
}

Explanation:

  • Named Exports:

    • export function greet(name) and export const PI = 3.14159; use the export keyword to make these specific functions and constants available for import as named exports.

  • Default Export:

    • export default function add(a, b) uses the default keyword before the function declaration. This makes the add function the primary exported entity from this module.

Importing in Another Module:

Key Points:

  • A module can have both named exports and a default export.

  • You import named exports individually using curly braces ({}), specifying the desired names.

  • To import a default export, you just use the module's filename as the imported value.

Last updated