Modules (ES6 modules, CommonJS)

Expert-Level Explanation

Modules in JavaScript are used to break up large codebases into smaller, manageable files (modules), each encapsulating specific functionality. ES6 modules use import and export statements to share code between files. CommonJS, used primarily in Node.js, uses require to load modules and module.exports to export them.

Creative Explanation

Think of modules as different departments in a company. Each department (module) handles its own specific tasks. In ES6 modules, import/export is like having a shared resource or service that departments can request or offer to others. CommonJS is like using internal mail (require) to request resources and sending out resources via a courier service (module.exports).

Practical Explanation with Code

ES6 Module:

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

// file: main.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5

CommonJS Module:

// file: math.js
function add(a, b) {
    return a + b;
}
module.exports = add;

// file: main.js
const add = require('./math.js');
console.log(add(2, 3)); // Output: 5

Real-world Example

Imagine a construction project (a software project). Each worker (module) has a specific skill, like plumbing or electrical work. They collaborate by using and providing services (code) to each other to complete the project.