w3resource

Export JavaScript Functions Inline for Modular Code


Exporting Functions Inline:

Write a JavaScript program to export a function directly during its definition and import it.

Exporting functions inline means directly exporting them during their definition. This approach eliminates the need for separate export statements and keeps the code concise.

Solution 1: Using Named Exports Inline

Code:

File: mathUtils.js

This file demonstrates exporting functions directly during their definition.

// mathUtils.js
// Exporting functions inline using named exports
export function add(a, b) {
  return a + b; // Adds two numbers
}
export function multiply(a, b) {
  return a * b; // Multiplies two numbers
}

File: main.js

This file imports and uses the named exports.

//main.js
// Importing the named functions
import { add, multiply } from './mathUtils.js';

// Using the imported functions
console.log(add(4, 5)); // Logs 9
console.log(multiply(3, 7)); // Logs 21

Output:

9
21

Explanation:

  • Functions add and multiply are exported inline during their definition using export.
  • In main.js, the functions are imported by their names and used directly.
  • This approach works well for exporting multiple specific functions.

Solution-2: Using Default Export Inline

Code:

File: greet.js

This file demonstrates exporting a single function as the default export.

// greet.js
// Exporting a function inline as the default export
export default function greet(name) {
  return `Hello, ${name}!`; // Returns a greeting message
}

File: main.js

This file imports and uses the default export.

//main.js
// Importing the default function
import greet from './greet.js';

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

Output:

Hello, Sara! 

Explanation:

  • The greet function is exported inline as the default export.
  • In main.js, the function is imported without braces, and a custom name can be assigned.
  • This approach is best when exporting a single primary function from a module.

For more Practice: Solve these Related Problems:

  • Write a JavaScript module that exports a function inline during its declaration and import it in another file.
  • Write a JavaScript module that defines and exports multiple functions inline and then calls them from another module.
  • Write a JavaScript module that uses inline export for an arrow function and demonstrates its usage in a calculation.
  • Write a JavaScript module that exports a function inline with a default parameter and test its behavior in an import.

Improve this sample solution and post your code through Disqus

Previous: Handle Circular dependencies in JavaScript Modules.
Next: Import JavaScript Modules for Side Effects.

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.