JavaScript

How to Export a Function in JavaScript

Sometimes, developers create multiple files and want to export some functions from one file to another file. JavaScript allows exporting and importing the functions or variables using the “export” or “import” keywords. For exporting functions, either define a function with the export keyword or export the already defined function.

This blog will explain the method to export a function in JavaScript.

How to Export a Function in JavaScript?

To export a JavaScript function, there are two ways.

  • Define a function with the “export” keyword
  • Export the already defined function

Syntax

To export a function, use the given syntax for defining the function with the “export” keyword

export function functionName() { /* ... */ }

Follow the below-given syntax to export the already defined function:

export {functionName}

Example 1: Export Already Defined Function

We have two JavaScript files, “info.js” and “JSfile.js”. In the given example, first, we will define a function in an “info.js” file for getting the user information using the “prompt()” method:

function getInformation(name, id){
 name = prompt('Enter Your Name');
 id = prompt('Enter Your id');
 console.log(name);
 console.log(id);
}

Now, export the function from the “info.js” file in “JSfile.js”:

export {getInformation};

The output shows that the function is successfully exported:

Let’s see the second way to export the function using the “export” keyword.

Example 2: Export Function With Export Keyword

Here, we will define the function “getInformation()” in “info.js” with an “export” keyword that will “import” in the <script> tag:

export function getInformation(name, id){
 name = prompt('Enter Your Name');
 id = prompt('Enter Your id');
 console.log(name);
 console.log(id);
}

In the <script> tag, import the function from “info.js”:

<script type="module">
 import {getInformation} from './info.js';
 console.log(getInformation());
</script>

Output

That’s all about exporting JavaScript functions from one JS file to another.

Conclusion

To export a JavaScript function, there are two ways: one is defining a function with the “export” keyword, and the other is exporting the already defined function. The function with the export keyword is imported in a JavaScript file or a script tag using “import {functionName} form ‘path’”. In this blog, we have explained the method to export a function in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.