The Module pattern encapsulates code using closures to create private state. ES6 modules are the standard with static imports (analyzed at compile time), while CommonJS uses dynamic require() at runtime. ES6 supports tree-shaking and async loading.
Classic Module Pattern:
CommonJS (Node.js):
require() for imports, module.exports for exportsES6 Modules:
import/export syntax// Revealing Module Pattern
const Calculator = (function() {
// Private state
let result = 0;
// Private function
function validate(n) {
if (typeof n !== 'number') throw new Error('Not a number');
}
// Public API
return {
add(n) {
validate(n);
result += n;
return this;
},
subtract(n) {
validate(n);
result -= n;
return this;
},
getResult() {
return result;
},
reset() {
result = 0;
return this;
}
};
})();
Calculator.add(5).add(3).subtract(2).getResult(); // 6
// Calculator.result is undefined (private)