Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Modular Programming with JavaScript
Modular Programming with JavaScript

Modular Programming with JavaScript: Modularize your JavaScript code for better readability, greater maintainability, and enhanced testability

eBook
₹799.99 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Modular Programming with JavaScript

Chapter 1. What Are Modules and Their Advantages?

In this very first chapter, I will provide you with an overview of the modular design approach in application development as it relates to JavaScript applications.

I will also mention parallels between the modular style of application architecture and the real-life examples of this conceptual design.

Hopefully, as you read along, you'll be able to relate to at least some aspects of the modular design approach and start to see why this style of organizing your code can be extremely beneficial.

The main objective of this chapter is to create a familiar context for you, and to get you started on thinking the modular way as you create and organize your code. Soon, you will see that this approach can organically grow into a well-defined application architecture methodology.

We will start the chapter with a brief discussion on how we can organize our code based on specialization. Then we will look at how we can define modules based on the functionality that they provide.

The topics that are covered in this chapter are:

  • The simple rule to creating modules
  • A real life example of modules
  • A look at a non-modular example
  • Re-factoring into a more modular approach
  • Designing in a modular way

Prelude to modular programming

Many years ago, when I was taking my first computer programming course at college, I found myself having having difficulty organizing my code into functions and classes. I always wondered what kind of criteria I needed to keep in mind to qualify a chunk of code as a function, a class or a subclass. When should I break down one function into multiple functions or a class into multiple classes?

Of course, there were some rules and guidelines that I was familiar with such as: "a function should not be too long or should not do too many things; a class should be a blueprint of a data type" and so on. However, such rules and guidelines seemed abstract to me and I wanted to find a rule that was precise and applicable in all situations.

As I became more knowledgeable in programming concepts and gained more experience in application design, I was able to write more sophisticated code and organize my code better into functions and classes.

However, while my code was organized into well-defined functions and classes, such functions and classes still seemed scattered in different parts of the application. When I needed to make modifications to one piece of the application, I would be concerned about the impact that the change would have on other pieces and the functionality of the application as a whole.

As my applications grew larger and became more complex, the impact of the changes and enhancements became even more pronounced. There were more things things that could adversely affect the application if the application pieces were not designed properly.

Browser-based applications were particularly vulnerable to such impacts as different parts of the application could be manipulating the same element in the browser, which would produce unexpected behaviors and effects in other parts of the application.

On the other hand, making small changes to the application was a challenge on its own, as finding the best place to make such small changes was not always very obvious. Each piece of the application could be performing many different activities from manipulation DOM to writing to cookie to making AJAX calls.

What if I could make one part of the application responsible for only one type of functionality? What if only one part of the application would be responsible for all cookie-related functionality? What if only one piece would make AJAX calls to the server and provide the other pieces of the application with the returned data?

As we design functions and classes to specialize in doing very specific tasks, we can also bundle such functions and classes together to act as a specialized piece of the application responsible for providing one particular functionality. The key point here is to create specialized code packages.

This would mean that changes in how we read and write to cookies would only take place in the package that is responsible for cookie operations and such changes would have no impact on how AJAX calls are made to the server.

If we organize our code into specialized packages, (or modules as we will call them) we can easily achieve this goal of separation of concerns and responsibilities among our application pieces.

But before we can organize our code into modules, we need to see how chunk of code can be considered a module

The simple rule for creating modules

I need to emphasize on the fact that modular programming is not some magical and mystical design concept and pattern that is hard to grasp and even harder to implement. It is really just a practical approach to organizing our code in such a way that each chunk of code only does a very specific and specialized task.

The idea is that each module is a loosely coupled piece of the application, a building block that, along with other pieces (and other modules), creates an ecosystem, that is your application.

So here is the simple rule for creating modules: "If a piece of your application provides a specialized functionality, it can be made into a module that can also be reused in other applications."

I mentioned previously that I was looking for a "precise" rule to help me organize my application code but as my experience has shown, there is no such precise rule other than what I mentioned above, which is in fact not a rule but a guideline. And as a guideline, there is flexibility in what can be considered a module or not. This can be best decided both at the design time and as the application evolves since the application needs can change over time.

A real-life example of modules

Let's consider a familiar modular system. You are most likely reading this book in a place that has electricity and there are many electric outlets in the walls surrounding you. This system enables you to plug in various electrical devices into the outlets and each one of these devices is designed to do a very specific task.

Consider the electrical devices that are plugged into some of these outlets: microwaves, electric kettles, washers, dryers, and so on.

None of these devices care if they are plugged into the electrical outlet in your house or your neighbor's house. They are designed to do their specific task and functionality when they are plugged in and when the power is on, regardless of whose house they are in.

Our application modules should follow the same philosophy. This means, regardless of where in the application they are plugged in and even regardless of what application they are plugged into, they should do their specific task and only their specific task.

Also, in exactly the same way that an electrical device can easily be unplugged from the wall outlet, a code module should be designed in such a way that it can easily be decoupled and removed from your application.

Furthermore, as the removal of one electrical device has no impact on the functionality of other devices that are plugged into your electrical system, the removal of a code module or a series of code modules from your application should not have any effect on the functionality of the other parts of your application.

This decoupling should also have no effect on the application as a whole, other than perhaps just losing the specific functionality that was provided by that particular module or group of modules in your application.

In this book, we will explore how creating modules will help in designing better specialized code pieces that can easily be plugged into and unplugged from our applications. We will also see how modular architecture provides for a more robust and flexible application as a whole.

We will discover how this kind of architectural approach leads to huge advantages in many aspects of our application fundamentals such as code usability, maintainability, testability, and many more.

I hope now you are curious enough to at least consider modular programming in general and JavaScript modular programming in particular as a possible approach for your future application design.

In further chapters, we will apply the same principles that we discussed regarding electrical outlets and appliances to our code modules, in both the design and implementation phases.

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:

function doAddition(num1, num2){
  return num1 + num2;
}

function doSubtraction(num1, num2){
  var result = null;
  if(num1 > num2){
  result = num1 - num2;

  }else{
    result = num2 - num1; 
  }
  return result;
}

console.log(doAddition(3,2)); // displays 5

console.log(doSubtraction(3,2)); // displays 1

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.

Re-factoring to a more modularized approach

Let's consider re-factoring the two functions that we looked at previously and putting them together in a more specialized package (class or module) called, CalculationHandler, as shown below:

function CalculationHandler(){
  CalculationHandler.result = null;
}

CalculationHandler.doAddition = function(num1, num2){
  return num1 + num2;
};

CalculationHandler.doSubtraction = function(num1, num2){

  if(num1 > num2){
    CalculationHandler.result = num1 - num2;

  }else{
    CalculationHandler.result = num2 - num1; 
  }
  return CalculationHandler.result;

};

console.log(CalculationHandler.doAddition(3,2)); // displays 5
console.log(CalculationHandler.doSubtraction(3,2)); // displays 1

As you can see in this "module" (and I use the term loosely here; you will see why in later chapters), I am using a function object and adding properties (methods) to this object. These methods do specialized tasks related to the overall functionality of the object (module), such as addition and subtraction.

Note

A note about our module here

If you are more experienced in JavaScript programming, you are probably thinking that the way I have created this module is probably not the best way to create a real module in JavaScript, and you are right! But for now, the big idea here is that any piece of code that does a specialized task can be tagged as a module, for the most part.

However, there are certainly better ways to write more robust and extensible modules in JavaScript. For instance, creating a module can be accomplished much better by using the Module Design Pattern, which we will get to explore a lot further in later chapters of this book.

Designing in a modular way

In the early stages of designing an application, one of the most important steps is to decide on the functionality that the application needs to provide. This of course, is based on the overall purpose of the application and the type of application that you are designing.

Based on such requirements, in the design phase, you should try to break down the overall functionality (the big picture) of the application into smaller and specialized pieces. Then, you can determine if such pieces already exist, either in the form of third-party libraries or the code that you have already written for a different application.

If you already have your own chunks of reusable code designed in a modular fashion (most third-party libraries are designed in such a way too), it would be much easier and quicker to connect these pieces together and use them in your new application. This would be the same as putting various Lego blocks together to create a play structure.

This type of approach is very important and fits quite well within an Agile development environment. This enables you to work on well defined, specialized modules as you need them and as new application requirements are defined. Also, as you create your code based on modules, you are able to prevent tight coupling among your application pieces.

On the other hand, this approach allows different developers to work on different pieces (modules) of the same application, independently of each other. Another advantage is that modules can be tested separately and in different environments before being added to the application.

In time and with more experience in modular application design and implementation, you will become better at deciding how to distinguish and design your modules. However, it is not realistic to think you can come up with the complete list of all the modules that you could ever need in your application, in the first attempt.

That is because applications evolve and requirements change over time. You may need to create new modules, or modify current ones, or decide to use a different module or library altogether to accommodate such changes in the requirements.

The key advantage of modular design is the flexibility that it provides. Dealing with all the situations mentioned above is a lot easier and requires a lot less effort in a modular architecture. It will also mitigate the impact that adding, removing, or modifying a module could possibly have on the application as a whole.

In the following chapters, you will see how we can create simple and complex modules and how they will be added to our application as loosely coupled pieces.

You will also see how we can load such modules dynamically and on demand when we need them in our application.

So, let's get ready for an exciting journey into our future application design, using modular architecture.

Summary

In this chapter, we tried to get an overview of the concepts behind modular programming in general and how such concepts can be used in JavaScript applications in particular.

We saw that this approach is essentially based on creating packages of specialized code that do very specific tasks.

We also made parallels between how modules are designed in real life and our application modules, so that we can translate the similarities into our own application design approach.

While the term "module" can be used to refer to different things in the code, we will take this terminology to refer to a certain style of programming and architecture in our JavaScript application design approach in later chapters.

However, before we completely dive into the more technical aspects of JavaScript modular programming, it is a good idea to review the fundamentals of object-oriented programming in JavaScript in the next chapter. This will allow us to establish a solid foundation for more technical chapters as we move forward.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Design and build fully modular, modern JavaScript applications using modular design concepts
  • Improve code portability, maintainability, and integrity while creating highly scalable and responsive web applications
  • Implement your own loosely coupled code blocks that can power highly maintainable and powerful applications in a flexible and highly responsive modular architecture

Description

Programming in the modular manner is always encouraged for bigger systems—it is easier to achieve scalability with modular programming. Even JavaScript developers are now interested in building programs in a modular pattern. Modules help people who aren’t yet familiar with code to find what they are looking for and also makes it easier for programmers to keep things that are related close together. Designing and implementing applications in a modular manner is highly encouraged and desirable in both simple and enterprise level applications. This book covers some real-life examples of modules and how we can translate that into our world of programming and application design. After getting an overview of JavaScript object-oriented programming (OOP) concepts and their practical usage, you should be able to write your own object definitions using the module pattern. You will then learn to design and augment modules and will explore the concepts of cloning, inheritance, sub-modules, and code extensibility. You will also learn about SandBoxing, application design, and architecture based on modular design concepts. Become familiar with AMD and CommonJS utilities. By the end of the book, you will be able to build spectacular modular applications in JavaScript.

Who is this book for?

If you are an intermediate to advanced JavaScript developer who has experience of writing JavaScript code but probably not in a modular, portable manner, or you are looking to develop enterprise level JavaScript applications, then this book is for you. A basic understanding of JavaScript concepts such as OOP, prototypal inheritance, and closures is expected.

What you will learn

  • Understand the important concepts of OOP in JavaScript, such as scope, objects, inheritance, event delegation, and more
  • Find out how the module design pattern is used in OOP in JavaScript
  • Design and augment modules using both tight augmentation and loose augmentation
  • Extend the capabilities of modules by creating sub-modules using techniques such as cloning and inheritance
  • Move from isolated module pieces to a cohesive, well integrated application modules that can interact and work together without being tightly coupled
  • See how SandBoxing is used to create a medium for all the modules to talk to each other as well as to the core
  • Use the concepts of modular application design to handle dependencies and load modules asynchronously
  • Become familiar with AMD and CommonJS utilities and discover what the future of JavaScript holds for modular programming and architecture

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 28, 2016
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781785880650
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 28, 2016
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781785880650
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 11,396.97
Mastering JavaScript Object-Oriented Programming
₹3649.99
Modular Programming with JavaScript
₹3649.99
Modern JavaScript Applications
₹4096.99
Total 11,396.97 Stars icon

Table of Contents

11 Chapters
1. What Are Modules and Their Advantages? Chevron down icon Chevron up icon
2. Review of Important JavaScript OOP Concepts Chevron down icon Chevron up icon
3. Module Design Pattern Chevron down icon Chevron up icon
4. Designing Simple Modules Chevron down icon Chevron up icon
5. Module Augmentation Chevron down icon Chevron up icon
6. Cloning, Inheritance, and Submodules Chevron down icon Chevron up icon
7. Base, Sandbox, and Core Modules Chevron down icon Chevron up icon
8. Application Implementation – Putting It All Together Chevron down icon Chevron up icon
9. Modular Application Design and Testing Chevron down icon Chevron up icon
10. Enterprise Grade Modular Design, AMD, CommonJS, and ES6 Modules Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(2 Ratings)
5 star 0%
4 star 50%
3 star 50%
2 star 0%
1 star 0%
Konstantin Jun 06, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
this is a fantastic book that teachers you how to build modular applications in javascript... and i am very happy i stumbled on it. It takes a very systematic approach towards the topic (building javascript applications using MVC/MV* patterns). I think the author has done a great job! There are some typos in the book though(that pretty much applications to all books)... that said, i cant recommend it enough! get it :-)
Amazon Verified review Amazon
RC Mar 26, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Had this book been published at the same time the ES5 standard was released (2009), I would give it 5 stars. The author does an excellent job at explaining how to create modules using IIFE (Immediately Invoked Function Expression), module augmentation techniques, OOP concepts, structural & behavior design patterns ( Facade, Mediator, Pub/Sub) and implements an excellent modular SPA (Single Page App) architecture based on Nicholas Zakas's 'Scalable JavaScript Application Architecture.'Because it was published after the release of the ES6/ES2015 standard, most of the content is dated. Since the release of ES2015 modules and modern browsers now supporting ES6 Modules, IIFE's are no longer the preferred technique to create modularity. The author dedicates only 4 pages to ES2015 modules.This book should have been about:1. How to migrate legacy IIFE modules to ES6 Modules2. How to use transpilers like Babel to create modules in ES6 and transpile back to ES5 module APIs (AMD, CommonJS, etc.).3. How to use tools like Webpack to support non-ES6 legacy browsers.4. Implementing the latest techniques for ES6 modules.In conclusion, the majority of the content is dated, however, one can still learn a lot on creating modularity with IIFE's and SPA modular architecture.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.