Modules – The Modern JavaScript Tutorial

A module is a file that contains code to perform a specific task. A module may contain variables, functions, classes, etc. 

As our program grows bigger, it may contain many lines of code. Instead of putting everything in a single file, you can use modules to separate codes into separate files as per their functionality. This makes our code organized and easier to maintain.

Modules can load each other and use special directives export and import to interchange functionality, and call functions of one module from another one.

export keyword labels variables and functions that should be accessible from outside the current module.

import allows the import of functionality from other modules.

Suppose, a file named person.js contains the following code

export function Person(name) {
    return `Hello ${name}`;

Now, to use the code of person.js in another file, you can use the following code:

import { Person } from './person.js';
let name = Person('Ankit');

console.log(name);      //Output :  Hello Jack        
Export Multiple Objects

We can also export multiple objects from a module.

In the file module.js

// exporting the variable
export const name = 'Programming Language';

// exporting the function
export function multiplication(x, y) {
   return x * y;

In main file,

import { name, multiplication } from './module.js';

console.log(name);          //   Output :  Programming Language      

let multy = multiplication(5, 7);

console.log(multy);         //   Output :  35        
Default Export

we can also perform a default export of the module. A file can contain multiple exports. However, you can only have one default export in a file.

export default function person(name) {
    return `Hello ${name}`;

export const age = 18;

Then when importing, you can use:

 import random_name from './person.js';        
Advantages of Module

Makes code reusable. You can define a module and use it numerous times as per your needs.

The code is easier to maintain because different codes having different functionalities are in different files.

Posted in

Ankit Patel

Leave a Comment

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

Scroll to Top