How to export multiple functions in JavaScript

In this article, we will learn about the export module in JavaScript. It allows you to export different sections of files into other files so that we can utilize the function in that file. It comes in handy when you want to build large-scale applications.

Exporting  multiple functions in JavaScript

Using export statements and we can export functions as their objects. In this way, we can use this function to export multiple functions. We make functions available to other files when we add them between curly brackets in the export statement.

In this example, we define our functions calc.js and then import them into another file called index.js. Then we add the script to index.html. In the script, we have to add type="module" to tell our browser that we are using modules inside this javascript file.

Example: Export multiple functions together

calc.js

function add(a,b) {
return a+b;
}
function sub(a,b) {
return a-b;
}
function mul(a,b){
return a*b;
}
export { add, sub }

index.js

import { add,sub } from "./calc.js";

console.log(add(56,34));
console.log((sub(10,2)));

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="module" defer src="index.js"></script>
    <title>Document</title>
</head>
<body>
    <h1>Here is the main page</h1>
</body>
</html>

Output

export multiple functions in JavaScript

Exporting functions one by one

Another way of exporting multiple functions is that we can add the word export before each function and then we can export the functions in another file.

Example:

calc.js

export function div(a,b) {
return a/b;
}
export function mul(a,b) {
return a*b;
}
export function mod(a,b){
    return a%b;
}

index.js

import { div,mul } from "./calc.js";
console.log("OUTPUT")
console.log(div(10,5))
console.log(mul(2,6))

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="module" defer src="index.js"></script>
    <title>Document</title>
</head>
<body>
    <h1>Another way!</h1>
</body>
</html>

Output:

Exporting functions one by one in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *