A look at a non-modular example
Let's consider an extremely simple example and see how the (somehow) specialized modular approach differs from a non-modular one.
We start by writing a couple of functions in the traditional way, as following:
As you can see in the above code, we have two independent functions for doing simple additions and subtractions and there is no relation between the two, other than the fact that they both operate on the two passed-in numbers (numeric values).
If we had implemented these functions in an application and were to do the identical operations in a different application, we most likely would either rewrite the same functions in that application from scratch or we would copy/paste the code from this application into the other one.
What if we now decided to also do multiplication, division, and other related calculations in our application using the same approach?
Well, one way would be to just continue writing independent functions as above and add them to our application. This approach could work and would get the job done, but probably not in the best way, since as the code grows it will become more disorganized and chaotic.
By using this approach, not only would we be polluting the global namespace with a bunch of global functions that could possibly collide with other global functions of the same name. We would also end up with scattered pieces of code that had not been packaged together based on their functionality and specialization.
If all such functions do mathematical calculations of one kind or another and that is the commonality that they all have, how about if we create a package (module) that specializes in mathematical calculations?
This would allow us to have a specialized package that regardless of the application that it is hosted in, would always provide the same specialized functionality.
Let's even imagine a step further and assume that we created this package in a separate JavaScript file that can be added as an independent module to any application.
Even better, how about if this module only would get added (requested from the server, in the case of a client side web application) to the application at runtime, and only when needed?
This type of implementation would give us the ability to load chunks, pieces, or modules of the code when needed at runtime and then unload them when the application does not need them anymore. This would enable us to cut down on the footprint of our application on the client side while providing all the necessary functionality as needed and on demand.
Such an approach can also be very useful on mobile devices which have limited bandwidth and resources to be leveraged.
Rest assured that I do intend to explore all such possibilities with you in the later chapters of this book.