Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to understand JavaScript module pattern?
The JavaScript Module Pattern is a design pattern that encapsulates private and public methods and variables within a single object. It provides a way to create modular, maintainable code while avoiding global namespace pollution.
What is the Module Pattern?
The Module pattern uses Immediately Invoked Function Expressions (IIFE) to create a closure that contains private variables and functions. It returns an object with public methods that can access these private elements.
Why Use the Module Pattern?
Maintainability ? Modules are self-contained and reduce dependencies, making code easier to maintain and improve independently.
Namespace Protection ? Variables outside function scope become global in JavaScript. The module pattern prevents "namespace pollution" where unrelated code shares global variables.
Reusability ? Modules can be easily reused across different projects without modification.
Encapsulation ? The pattern encapsulates private methods and variables, exposing only the public interface. This protects internal implementation from external interference.
Basic Module Structure
var myModule = (function() {
// Private variables and functions
var privateVar = "I'm private";
function privateFunction() {
return "Private function called";
}
// Return public interface
return {
publicMethod: function() {
return privateFunction();
},
publicVar: "I'm public"
};
})();
Example: Age Filter Module
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Age Filter Module</title>
</head>
<body>
<script>
var ageModule = (function() {
var ages = [10, 20, 15, 50, 27, 17, 22, 87, 65, 45];
function calculateAverage() {
var total = ages.reduce(function(sum, age) {
return sum + age;
}, 0);
return total / ages.length;
}
function getNotQualified() {
var minors = ages.filter(function(age) {
return age < 18;
});
return minors.length;
}
return {
getAverageAge: function() {
return "Average age: " + calculateAverage().toFixed(1);
},
getMinorCount: function() {
return "Ages less than 18: " + getNotQualified();
}
};
})();
document.write(ageModule.getMinorCount() + "<br>");
document.write(ageModule.getAverageAge());
</script>
</body>
</html>
Ages less than 18: 3 Average age: 35.8
Example: Counter Module with Private State
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Counter Module</title>
</head>
<body>
<script>
var counter = (function() {
var count = 0; // Private variable
function print(message) {
document.write(message + " - Count: " + count + "<br>");
}
return {
get: function() {
return count;
},
set: function(value) {
count = value;
},
increment: function() {
count++;
print("After increment");
},
reset: function() {
print("Before reset");
count = 0;
print("After reset");
}
};
})();
counter.increment();
counter.increment();
counter.set(7);
document.write("Counter Value: " + counter.get() + "<br>");
counter.reset();
</script>
</body>
</html>
After increment - Count: 1 After increment - Count: 2 Counter Value: 7 Before reset - Count: 7 After reset - Count: 0
Key Benefits
The module pattern provides true privacy for variables and functions. External code cannot directly access the count variable or print function - they can only interact through the public interface.
Conclusion
The JavaScript Module Pattern is essential for creating clean, maintainable code. It provides encapsulation, prevents namespace pollution, and creates reusable components with clear public interfaces.
