Module Pattern
The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern that is used to wrap a set of variables and functions together in a single scope.
Last updated
The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern that is used to wrap a set of variables and functions together in a single scope.
Last updated
Some time ago, a popular approach would be to enclose a piece of code in an Immediately Invoked Function Expression (IIFE). This is because all JavaScript files share the same scope.
index.html
hello.js
main.js
The fact that defining something in one file pollutes the whole global scope is not a desirable situation. A common way to solve this was to introduce the module pattern by creating a function and immediately invoking it.
hello.js
main.js
An important thing about the above approach is that if we define any variable inside the above module, it is not available outside of it.
We can also export the hello function by returning something from our Immediately Invoked Function Expression.
hello.js
main.js
As the JavaScript language evolved, we found other ways to deal with the above issue. One of them are ES6 modules, where every module has its file. Modern browsers already support them. You can also use them with Webpack.
Node.js environment also provides its solution by implementing a module system called CommonJS. Let’s examine an odd piece of code:
It seems weird because the return statement can’t occur outside of a function. When we import such a file, Node.js wraps it in a function like this:
Thanks to the above, the module has its own scope, and the above code runs without errors.