Modular JavaScript
From Wikipedia: In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.
The Module Pattern is one of the most common design patterns used in JavaScript.
A module is a piece of program that specifies which other pieces it relies on and which functionality it provides for other modules to use. It is created as an IIFE (Immediately-Invoked Function Expression).
Module interfaces make part of the module available to the outside world and keep the rest private.
Anonymous Closures
This is the fundamental construct that makes modules possible. All of the code that runs inside the function lives in a closure, which provides privacy throughout the lifetime of our application.
In this example both var sum and function privateMethod are private properties of myModule. When we are accessing a module, we are accessing whatever it returns.
Get Gia Edgington’s stories in your inbox
Join Medium for free to get updates from this writer.
Exporting Modules
To get access to module features, we need to export them. This is done using the export statement.
We can either place it in front of any items we want exported out of the module or we can use the module.exports object to expose it.
Dependencies
The relations between modules are called dependencies. When a module needs a piece from another module, it is said to depend on that module. When this fact is clearly specified in the module itself, it can be used to figure out which other modules need to be present to be able to use a given module and to automatically load dependencies. To get access to modules needed we only have to import them:
Why use modules?
Modules provide structure to bigger programs by separating the code into pieces with clear interfaces and dependencies. Also have maintainability, because they are self-contained and reusability.





