/

Exporting Multiple Functions in JavaScript

Exporting Multiple Functions in JavaScript

In JavaScript, you can divide a program into separate files to improve organization and reusability. But how do you make the functions defined in one file accessible to other files? In this article, we will explore how to export multiple functions from a JavaScript file.

Let’s say you have a JavaScript file where you define a few functions, like this:

1
2
3
4
5
6
7
function sum(a, b) {
return a + b;
}

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

To make these functions available to other files, you can use the export keyword. Here’s the syntax to export multiple functions:

1
export { sum, mul };

Now, other files can import these exported functions. You can either import all the functions or selectively import only the ones needed. Here are a couple of examples:

1
2
import { sum, mul } from 'myfile';
import { mul } from 'myfile';

By importing these functions, you can use them in your code just like any other locally defined function.

In summary, exporting multiple functions from a JavaScript file involves using the export keyword followed by the names of the functions you want to export. Other files can then import these functions using the import keyword, either importing specific functions or importing all of them. This allows for greater modularity and code reuse in your JavaScript applications.

tags: JavaScript, export, functions, modularization, code reuse