How to export a function in JavaScript

Export a Function in JavaScript

Export is an essential technique if you want to work with Javascript. Specifically, in this article, we will learn how to export a function in JavaScript. Let’s read it now.

Export a function in Javascript

Export by the name of function

Use functions and variables exported from one module to another in other files. Stateless components can be used in other components by exporting a function from respective modules and using it in other files, strictly in Javascript.

This way, we will put the function to be exported into a pair of brackets {}, the function must be defined before, and the Javascript file will know which function is being exported.

Code:

function showMessage() {
	var message = "Welcome to LearnShareIT";
	console.log(message);
}

showMessage();
export { showMessage };

Output:

In JavaScript ES6, named export is used to export many things from a module by adding the export keyword to their declaration. Exported things will be distinguished by name. Then import the ones we need to use by surrounding them with curly braces { }. The name of the imported module must be the same as the name of the exported module.

In the HTML file, when you want to import a function from a javascript file, you must use a script tag with the type “module” so that the program can receive an imported module with functions inside. In this way, you can export multiple functions in the same file by enclosing their names in curly braces of export, and the program will do the rest for you. Or you can also refer to the method below.

Using the export function method

By exporting this function, you must export the functions one by one by adding export in front when we define the function. When running the program, Javascript will run from top to bottom, recognize the exported code, and export each function.

Code:

export function showMessage() {
	var message = "Welcome to LearnShareIT";
	console.log(message);
}

showMessage();

The return results of the two ways are the same. The showMessage function has been exported and can be used when we import it into another Javascript file. However, you will have to write export functions one by one in the export function method. There are better ways than this.

Summary

In summary, the article has shown you how to export a function in JavaScript. Although giving the same result, we recommend you to use the export method with {} syntax because you can export many functions by writing their names inside.

Maybe you are interested:

Leave a Reply

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