In early JavaScript, applications were single monolithic scripts polluting the global window object. ES Modules (ECMAScript Modules / ESM) introduced official, standardized language-level modularity in ES6, allowing software systems to be organized into clean, reusable, encapsulated files.
// mathUtils.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.js
import { add, PI } from "./mathUtils.js";
console.log("Sum:", add(10, 20)); // 30
console.log("PI Value:", PI);
// StudentService.js
export default class StudentService {
static getStudentById(id) {
return { id, name: "Vikram" };
}
}
// main.js (No curly braces needed for default exports!)
import StudentService from "./StudentService.js";
const student = StudentService.getStudentById(101);
import()) - Code SplittingAllows loading modules on-demand only when a user triggers an action (saving initial page load time):
button.addEventListener("click", async () => {
// Loaded dynamically on-demand!
const { generatePDFReport } = await import("./pdfGenerator.js");
generatePDFReport();
});
Exam Question: "Compare CommonJS (Node.js legacy) and ES Modules (ESM)."
| Feature | CommonJS (CJS) | ES Modules (ESM) |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| Loading Nature | Synchronous & Dynamic (at runtime) | Asynchronous & Static (at parse time) |
| Tree-Shaking | Difficult / Not supported | Natively supported |
How do you write pure functions, currying, and memoization pipelines? Proceed to: JavaScript Functional Programming & Currying →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Packaging and exporting reusable classes.
Exporting pure utility functions.
Setting up type="module" and script tags.