JavaScript - JavaScript Modules (ES Modules)

JavaScript Modules are a way to organize code into separate files so that each file contains a specific part of the program. This helps developers manage large applications more easily. Instead of writing all the code in one file, modules allow you to split the code into smaller, reusable pieces.

ES Modules (ECMAScript Modules) were officially introduced in ECMAScript 2015. They use the keywords export and import to share code between different files.

A module can export variables, functions, classes, or objects so that other files can use them.

Example of exporting from a module:

// math.js
export function add(a, b) {
    return a + b;
}

export function multiply(a, b) {
    return a * b;
}

In this example, the functions add and multiply are exported from the file named math.js.

Another JavaScript file can import these functions and use them.

Example of importing a module:

// app.js
import { add, multiply } from './math.js';

console.log(add(5, 3));
console.log(multiply(5, 3));

Here, the import statement loads the exported functions from math.js so they can be used in app.js.

JavaScript also supports default export, which allows a module to export one main value.

Example:

// message.js
export default function showMessage() {
    console.log("Hello from module");
}

Importing a default export:

import showMessage from './message.js';

showMessage();

Modules are executed in strict mode by default, and variables inside a module are scoped to that module. This prevents global variable conflicts.

Modules improve code organization, reusability, and maintainability. They are widely used in modern JavaScript development, especially in frameworks and large web applications.