w3resource

Mastering JavaScript Default Exports and Imports


Default Export:

Write a JavaScript module that exports a default function to greet a user and use it in another file.

Solution-1:

JavaScript Code:

File: greet.js

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

File: app.js


// --- file: app.js ---
// Import the default function
import greet from './greet.js';

// Use the imported function
console.log(greet('Sara')); 

Output:

Hello, Sara!

Explanation:

  • greet.js exports a default function called 'greet'.
  • app.js imports it using 'import greet from './greet.js';'.
  • The function is invoked to greet the user Alice.

Solution-2:

JavaScript Code:

File: greetings.js

// --- file: greetings.js ---
// Export a default function
const greet = (name) => {
  return 'Hi, ${name}! Welcome!';
};
export default greet;

File: main.js

// --- file: main.js ---
// Import the default function
import greet from './greetings.js';

// Use the imported function
const message = greet('Bob');
console.log(message);  

Output:

Hi, Bob! Welcome!

Explanation:

  • greetings.js defines a default exported function using an arrow function syntax.
  • main.js imports the default export using the 'import' statement.
  • The function is used to generate a greeting message for Bob.

Improve this sample solution and post your code through Disqus

Previous: JavaScript Import/Export Exercises Home.
Next: Named Exports in JavaScript for Arithmetic Operations.

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.