Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

JavaScript Modules

JavaScript Modules allow us to divide a large JavaScript program into smaller, reusable and manageable files.

What are JavaScript Modules?

A module is a separate JavaScript file that contains related variables, functions, classes, or other code.

Modules help us organize our application and reuse code between different JavaScript files.

Simple Definition

JavaScript Modules allow us to export code from one file and import that code into another file.

JavaScript Modules math.js function add() export Reusable Code → import app.js import { add } use function Application Code → Result 30 Export → Import → Reuse

One JavaScript file can export code and another JavaScript file can import and reuse it.

How JavaScript Modules Work
Create Module
→
export
→
import
→
Reuse Code

Export

The export keyword makes a variable, function, or class available to other JavaScript modules.

export function add(a, b) {
    return a + b;
}
Function exported successfully.

Import

The import keyword is used to use exported code inside another JavaScript module.

import { add } from "./math.js";

let result = add(10, 20);

console.log(result);
30

Named Export

Multiple variables or functions can be exported from the same module.

export const name = "Rahul";

export function greet() {
    return "Hello " + name;
}
Hello Rahul

Default Export

A module can have one default export.

export default function greet() {
    return "Welcome to CIIT Training Institute";
}
Welcome to CIIT Training Institute

Benefits of JavaScript Modules

Benefit Description
Code Organization Divides large applications into smaller files.
Code Reusability Code can be imported and reused.
Maintainability Smaller files are easier to manage.
Separation Different parts of an application can be kept separate.
Important Points

• export makes code available to another module.

• import brings exported code into another module.

• Modules help organize large applications.

• Modules improve code reusability and maintainability.

Summary

JavaScript Modules allow developers to split code into separate files. The export keyword shares code from a module, while the import keyword allows another module to use that code.