HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Modules

JavaScript modules allow you to split your code into separate files, each containing its own functionality, variables, and functions, and then import and export these modules as needed.


There are two types of exports: Named Exports and Default Exports.

Export

Modules with functions or variables can be stored in any external file.

Named Exports

Let us create a file named person.js, and fill it with the things we want to export.

You can create named exports two ways. In-line individually, or all at once at the bottom.

person.js

In-line individually:

export const name = "Jesse";
export const age = 40;              
              

person.js

All at once at the bottom:

const name = "Jesse";
const age = 40;

export {name, age};            
              

Default Exports

Let us create another file, named message.js, and use it for demonstrating default export.

You can only have one default export in a file.

Example

const message = () => {
const name = "Jesse";
const age = 40;
return name + ' is ' + age + 'years old.';
};

export default message;           
You can click on above box to edit the code and run again.

Output