Modular Programming in JavaScript

I was learning ES6 about two weeks ago, and it reminded me of how modular programming in JavaScript was done during the years prior. I’m quite happy with how JavaScript has evolved, I would even say that I’m starting to like it. Before we go into the “How to do modular programming in JavaScript today”, I would like to give my thoughts on modular programming first.

Modular Programming

Modular programming is about chopping down a big idea (which is the program itself) into little ideas (the program’s features). You then build each of those little ideas and connect them together to create the big idea. This programming style allows you to create software that is easier to maintain – I’m in the opinion though that if you overdo it, your software will be even harder to understand and maintain.

How is modular programming done in JavaScript

When I first learned C#, modular programming was something I felt closer to – I want to make small methods, and small classes. Separating your code into smaller classes is built-into C#, and this was not the same with JavaScript. When I first learned JavaScript, there was a weird hack to separate your code into its own modules. You have to use a function that is invoked right after its creation – the term IFFE was coined for this behavior.

The addition of the import and export statements in ES6 means modular programming is now supported natively in JavaScript – I don’t have experience with Node.js so I have no clue if ES6 imports and exports also work out-of-the-box there like in current Web Development.

Below is an extremely quick rundown of how modular programming evolved in native JavaScript:

  1. A smart developer thought about IFFE, and the Module Pattern was born in JavaScript
  2. CommonJS and other libraries made improvements to IFFE, and solved the problems with using it to create modules – like script files should be loaded in order correctly, and some other problems
  3. ES6 adopted the improvements from CommonJS et al, made some tweaks to it, and now we have module support in native JavaScript

I’m sure there are tons of resources around the web if you want to know more details about how modules evolved in JavaScript, and how to do it, so I won’t include it in this post.