JavaScriptMedium
What is the Module pattern and how does it help with encapsulation?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
The Module pattern in JavaScript is a design pattern used to create self-contained modules of code. It helps with encapsulation by allowing you to define private and public members within a module. Private members are not accessible from outside the module, while public members are exposed through a returned object. This pattern helps in organizing code, avoiding global namespace pollution, and maintaining a clean separation of concerns.
js
var myModule = (function () {
var privateVar = "I am private";
function privateMethod() {
console.log(privateVar);
}
return {
publicMethod: function () {
privateMethod();
},
};
})();
myModule.publicMethod(); // Logs: I am private
