Advertisement
728x90
Module pattern is a designed pattern used to wrap a set of variables and functions together in a single scope returned as an object. JavaScript doesn't have access specifiers similar to other languages(Java, Python, etc) to provide private scope. It uses IIFE (Immediately invoked function expression) to allow for private scopes. i.e., a closure that protect variables and methods.
The module pattern looks like below,
javascript
1(function () {
2 // Private variables or functions goes here.
3
4return {
5 // Return public variables or functions here.
6};
7})();Let's see an example of a module pattern for an employee with private and public access,
javascript
1const createEmployee = (function () {
2 // Private
3
4const name = "John";
5
6const department = "Sales";
7
8const getEmployeeName = () => name;
9
10const getDepartmentName = () => department;
11
12// Public
13
14return {
15 name,
16 department,
17 getName: () => getEmployeeName(),
18 getDepartment: () => getDepartmentName(),
19};
20})();
21
22console.log(createEmployee.name);
23
24console.log(createEmployee.department);
25
26console.log(createEmployee.getName());
27
28console.log(createEmployee.getDepartment());Note: It mimic the concepts of classes with private variables and methods.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 20
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
449of476