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.
File: main.js
This file imports and uses the named exports.
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.
File: main.js
This file imports and uses the default export.
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.