Module
A module is a self-contained unit of code that encapsulates related functionality and can be imported and reused across different parts of an application.
ES6 Modules
Modern JavaScript uses the ES6 module system:
javascript// math.js - Exporting export const add = (a, b) => a + b export const subtract = (a, b) => a - b export default multiply = (a, b) => a * b // app.js - Importing import multiply, { add, subtract } from './math.js'
Benefits
Encapsulation Keep code organized and prevent naming conflicts.
Reusability Use the same code in multiple places.
Maintainability Easier to update and debug isolated units.
Dependency Management Clear dependencies between code units.
Module Formats
ES6 Modules (ESM) Native JavaScript modules, supported in modern browsers.
CommonJS
Node.js module system using require() and module.exports.
AMD (Asynchronous Module Definition) Older format for browser-based modules.
UMD (Universal Module Definition) Works in both browser and Node.js environments.
Example
javascript// user.js export class User { constructor(name) { this.name = name } greet() { return `Hello, ${this.name}` } } // app.js import { User } from './user.js' const user = new User('Alice') console.log(user.greet())