JavaScript – How to export multiple functions from a file

In this article, we will learn about different approaches to export multiple functions from a single Javascript file.

In Javascript, ES6 has made it really easy to export multiple functions or variables from a javascript file in our projects.

So let’s see each approach with an example.

Export multiple functions using export statement

The easy and simple way to export all the functions from a js file is to use the export statement.

Example:

function sum(a,b){
    return a + b;
}

function multiple(a,b){
    return a * b;
}

export { sum , multiple }

As you can see, to make them available for other files, we have to export them in curly brackets syntax { } .

Another way, since most modern projects, use JavaScript with ES6 or later, we can just add the export statement before the function definitions. For Example,

file1.js

export function sum(a,b){
    return a + b;
}

export function multiple(a,b){
    return a * b;
}

This will directly export the function, we do not have to write it in the curly bracket { } as shown in the first example.

We can use the export statement in the js file as many times as we want.

Now, once we have exported multiple functions from a Javascript file, we can use those functions in other files in our project using the import statement.

To import we can consider the module (i.e the js file) as an object and use destructuring. For example:

file2.js

import { sum, multiple } from 'file1.js'

Or if you only want to import one function,

import { sum } from 'file1.js'

Export multiple variable or arrow functions in JavaScript.

Now, to export multiple variables or arrow functions in Javascript we use the same export statement before the JavaScript variables.

The only difference you can see is that this time instead of exporting functions, we are exporting multiple variables. For example:

file3.js

export const sum = (a,b) => a*b;
export const message = 'This is export and import In JavaScript'

And to import these functions we use the same syntax as above.

import { sum , message } from 'file3.js'

So, these are the simple ways to export and import multiple functions in ES6 JavaScript.

However, if you are not using ES6 or a later version in your project, then you have to use the module.exports to export multiple functions from a file. For example:

function sum(a,b){
    return a + b;
}

function multiple(a,b){
    return a * b;
}

module.exports = { sum , multiple }

That’s it, these are the quick ways you can export or import more than one function from/to a Javascript file.

Scroll to Top