What is up! fellow coders.
Quick disclaimer: I'm a month into a coding bootcamp, but am confident this could help others like myself understand module pattern from a beginner perspective.
So lets begin.
First, to understand The Module pattern(MP) you need to understand what is a module.
Modules are an integral part of any large application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.
Yes. but first
The Module pattern (MP) was originally defined as a way to provide both private and public environment for classes in software engineering.
Your take away from that should be "the module pattern is one of the methods that uses a module to keep certain codes, variables,functions, etc. inside a single object, so it doesn't pollute the global scope. Thus keeping our code clean and organize "
Lets take a look at an example of a module pattern and break it down.
I made a module using an IIFE and called it "myModule".
Inside the module I declared a variable myGreeting ,an object called myObject and 2 functions saySomething and sayGreeting.
Inside my function I can reference variables like myGreeting in both the functions and even a property of an object the name and food from myObject.
Then you can see from line 18-22 I made a variable called public API in order to reference the 2 function inside my module and to return them.
Lastly because of the public API and my ability to return the function I can now call the 2 function on line 26 and 28.
Therefore, what makes myModule a module pattern is how I was able to make everything inside private from the global scope. Thus the only way to return the function inside is by using the public API that reference them.
Of course my example was very simple, but just imagine how important this method can be when dealing with a robust amount of code on a large project with multiple developers working on it. The module pattern can keep the global scope clean and organize and prevent duplicate variables from overriding each other.