w3resource

Mastering Default and Named Exports in JavaScript Modules


Combining Default and Named Exports:

Write a JavaScript module with both default and named exports. Use both in another file.

Solution-1:

JavaScript Code:

File: utility.js

// --- file: utility.js ---
// Export a default function
export default function greet(name) {
  return `Hello, ${name}!`;
}

// Export named functions
export function add(a, b) {
  return a + b;
}

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

File: app.js

// --- file: app.js ---
// Import both default and named exports
import greet, { add, subtract } from './utility.js';

// Use the imported exports
console.log(greet('Darek'));         // Output: Hello, Darek!
console.log(add(10, 5));             // Output: 15
console.log(subtract(10, 5));        // Output: 5
 

Output:

Hello, Darek!
15
5

Explanation:

  • 'utility.js' combines a default export ('greet') and named exports ('add' and 'subtract').
  • 'app.js' imports the default export and named exports in one statement.
  • The default export ('greet') is used without curly braces, while named exports require them.
  • This pattern allows for flexibility in how the module is consumed.

Solution-2:

JavaScript Code:

File: mathUtils.js

// --- file: mathUtils.js ---
// Default export: main operation function
export default function calculate(a, b, operation) {
  switch (operation) {
    case 'add':
      return a + b;
    case 'subtract':
      return a - b;
    case 'multiply':
      return a * b;
    case 'divide':
      return b !== 0 ? a / b : 'Cannot divide by zero';
    default:
      return 'Invalid operation';
  }
}

// Named exports: specific operations
export function square(a) {
  return a * a;
}

export function cube(a) {
  return a * a * a;
}

File: main.js

// --- file: main.js ---
// Import default and named exports
import calculate, { square, cube } from './mathUtils.js';

// Use the imported exports
console.log(calculate(10, 5, 'add'));   // Output: 15
console.log(square(4));                 // Output: 16
console.log(cube(3));                   // Output: 27

Output:

15
16
27

Explanation:

  • 'mathUtils.js' exports a default function ('calculate') and two named functions ('square' and 'cube').
  • 'main.js' imports the default export and named exports in one statement.
  • This pattern allows the default function to handle complex logic while named exports focus on specific tasks.

Improve this sample solution and post your code through Disqus

Previous: Mastering import all as alias in JavaScript.
Next: Re-exporting in JavaScript Modules for better code management.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.