Clean β’ Professional
JavaScript Modules are a way to organize code into reusable, independent pieces, improving maintainability, readability, and scalability. Modules allow developers to split a large codebase into smaller, self-contained files, each responsible for a specific task. Modules can export variables, functions, or classes and import them into other modules, promoting code reusability and encapsulation.
1. Encapsulation
Modules encapsulate their own scope. Variables and functions declared inside a module are not added to the global scope, avoiding naming conflicts.
2. Reusability
You can reuse modules across different projects or parts of an application by exporting and importing functionality.
3. Maintainability
Breaking code into modules makes it easier to maintain, test, and debug.
4. Lazy Loading (Dynamic Imports)
Modules can be loaded dynamically only when needed, improving performance.
Modules can export values, functions, or classes so that other modules can import them.
Named Exports:
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
Default Export:
Each module can have a single default export, useful for main functionality.
// calculator.js
export default function subtract(a, b) {
return a - b;
}
Modules can import exported features from other modules.
Import Named Exports:
// main.js
import { PI, add } from './math.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159
Import Default Export:
import subtract from './calculator.js';
console.log(subtract(5, 2)); // 3
Import All as Namespace:
import * as math from './math.js';
console.log(math.add(4, 6)); // 10
console.log(math.PI); // 3.14159
Modules can be loaded asynchronously with import(), which returns a Promise.
async function loadModule() {
const math = await import('./math.js');
console.log(math.add(10, 5)); // 15
}
loadModule();
1. ES Modules (ESM)
import and export..mjs extension or "type": "module" in package.json).2. CommonJS Modules
Β
require() and module.exports.Example:
// utils.js
function greet(name) {
return `Hello, ${name}`;
}
module.exports = greet;
// main.js
const greet = require('./utils.js');
console.log(greet('John')); // Hello, John