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 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.
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:
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.