The module pattern packages related JavaScript behavior inside one immediately invoked function expression. It hides internal variables and helper functions while returning an object that exposes the intended public API, reducing global references. section 2.4
function zipCode(code, location) {
let _code = code;
let _location = location || '';
return {
code: function () {
return _code;
},
location: function () {
return _location;
},
...
};
}
A closure lets returned methods read private variables without exposing those variables directly. section 2.4
Private state behind public methods
A zip-code factory can retain its code privately and expose access through a method: const princetonZip = zipCode('08544', '3345'); princetonZip.code(); // '08544'. The caller uses the method, not the hidden variable. section 2.4
The pattern provides three practical benefits:
- Encapsulates internal state and behavior. section 2.4
- Limits the global namespace and shared data. section 2.4
- Supports functional code organized into well-encapsulated modules. section 2.4

