

But when our software is modular, each of its modules can be built and maintained in isolation. Isolation: Understanding the whole system can be difficult and time-consuming.Also, it enables us to protect private properties and methods from being accessed from other parts of our code, as we have seen in our example above. This enables us to logically-organize different units of our code. And any developer can download and use these modules in their application. The npm registry hosts the world’s largest collection of free, reusable modules. Modules can easily be composed because they explicitly define their imports and exports. Thus, we can isolate and reuse our code.Īlso, a module can be beneficial to more than one program, and in these cases, we can create a package.Ī package can contain more than one module and can be uploaded to a service like npm, from where it can be downloaded by anyone who needs it. Modules maximize reliability since we can import and use them from any of our modules. Now using the IIFE module pattern discussed above, we can create a module that exports an interface.īelow are some of the benefits of using modules or the module pattern in JavaScript: What we export from our module is available for use to whoever imports our module. The exports: This is the interface to the module.The code: This refers to the actual code of our module.Also, to use utility libraries like Lodash, we need to install and import it as a dependency. For example, to create a React component, we need to import the React module. In this case, we can import the required module as a dependency.

The Module patternĪ module can require another module to work properly. In the next section, we will take a deeper dive into the module pattern in JavaScript. If you have difficulty understanding the concept of closures and scopes used in our example above, kindly read our article that covers these topics. Note the error from the second console.log statement is the behavior we want as it shows that the variable does not leak to the global scope.
