Modularity

Partitioning your code base in standalone, independent units.

Large JavaScript applications are easier to manage and maintain when they are modular.



Overview


When an application is said to be modular, it means that it has well-defined units of functionality are relatively independent from each other (that is, they are loosely coupled). Suppose you have an app that maintains Employee data. You may see modules like Employees, Admin, Reporting, and some cross-cutting modules, such as, Ajax, Security, and Utils (note: cross-cutting means they affect all areas in the app). Modularity is beneficial because it brings clarity to your code base; the programs are easier to understand, easier to test, and easier to maintain.

Most languages allow you to organize a large body of code in modular units. JavaScript does not natively support this, but the Module pattern allows us to organize the code into clearly defined units called modules. Usually there is one module per file.

The next step is the ability to import these modules where necessary. Most languages support native syntax for this, such as, import, using, or require. JavaScript does not have this and there is no easy way to import modules and help with the dependency management of these modules.

The ES6 (EcmaScript 6) proposal addresses the problem head-on with a new module system and the addition of these keywords: module, export, and import. Unfortunately, it will take some time before JavaScript developers are generally coding against the new ES6 standard.

In the meantime, many developers building large systems use an alternative called AMD (Asynchronous Modular Definition). AMD is a protocol: its goal is to provide a modular development API that allows JavaScript to define modules and their dependencies that can be loaded asynchronously (notice how script loading comes into play again).

In the next section we will review the AMD format specification as well as the most popular open-source tool that implements it: Require.js.