IIFE
: Immediately invoked function expression
The module scope can be used to share the variables between different functions so that we can share things without having to go through the Global Scope in this way with a module scope we can be explicit which variables, classes, or functions in the module. JavaScript decided to use closure and encapsulation to create our own module.
- Global Scope
- Module Scope
- Function Scope
- Block Scope – Let and Const
- Function Scope
- Module Scope
const moduleOne = (function () {
let name = "Tim";
let phone = {
Apple: "IPhone",
Samsung: "Galaxy",
};
function addTwo(x) {
return x + 2;
}
return {
name,
phone,
addTwo,
};
})();
console.log(moduleOne.name);
console.log(moduleOne.phone.Apple);
console.log(moduleOne.phone.Samsung);
console.log(moduleOne.addTwo(3));
Tim
IPhone
Galaxy
5
This pattern is what we need is actually called the revealing module pattern. We just reveal whatever we need so we can have private functions if we want or private variables if we want as we know because of closure even though the function gets executed because we returning a function inside of a function.
JQuery is also the same pattern.