What Are Modules in JS and How to Use Them?

What Are Modules in JS and How to Use Them?

JavaScript is a popular programming language that is widely used for web development. It has evolved over the years, and one of the significant changes that came with the introduction of ES6 (ECMAScript 2015) is the module system.


In JavaScript, modules are a way of organizing code into reusable, independent, and encapsulated units. Developers can use a module, which is a file containing code that can be imported and utilized by other parts of the application, to create self-contained functionality that can be shared across different parts of the application. This makes the code more modular, maintainable, and scalable.

Importing and Exporting Modules in js

To use a module in JavaScript, you need to import it into your code. The import statement is used to import a module, and it looks like this:

import moduleName from './module-file.js';

Here, moduleName is the name you want to use to refer to the module in your code, and ./module-file.js is the relative path to the module file.

In the module file, you need to use the export statement to make the code available for import. There are two types of exports: default and named.

Default Export

To create a default export, you need to use the export default statement like this:

const myFunction = () => { ... };
export default myFunction;

Here, myFunction is the function you want to export as the default value.

To import a default export, you don’t need to use curly braces, and you can use any name you want to refer to the default export, like this:

import myFunction from './module-file.js';

Named Export

To create a named export, you need to use the export statement like this:

export const myFunction1 = () => { ... };
export const myFunction2 = () => { ... };

Here, myFunction1 and myFunction2 are the functions you want to export as named exports.

To import named exports, you need to use curly braces and the exact name of the export, like this:

import { myFunction1, myFunction2 } from './module-file.js';

Benefits of Using Modules in js


Modules allow you to encapsulate code into independent units, which makes it easier to manage and maintain the code. Encapsulation also helps to prevent naming collisions and reduces the risk of unintended side effects.


Modules make it easy to reuse code across different parts of the application, which can save time and improve code quality. By creating reusable modules, developers can avoid duplicating code and reduce the overall size of the application.


Modules allow you to break down a large application into smaller, more manageable pieces, which can make it easier to scale the application. By using modules, developers can add new features or make changes to the codebase without affecting other parts of the application.

Follow Us on

Read More

Related Post

Leave a Reply

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