Modular Object Coding Pattern in JavaScript Vs Basic Coding Style

Allure Web Solutions Code Snippet

There are many ways to write JavaScript functions. The concept of different styles of writing code can be classified under the term Design Patterns. Some patterns are better than others. In our quest to write the most readable, modular, re-useable, optimized, and beautiful code, we constantly search for the best pattern.

If you’re new to JavaScript, it can be hard to wrap your mind around the concept of “object oriented.” Everything in JavaScript is basically an object. Below I show two patterns for a very basic waiting list. Both pieces of code perform example the same functionality. The code on the right most closely resembles the Module Design with Single global variables namespacing.

A few reasons why the code on the right is better than the code on the left:

  • Completely Modular: You can take this fully self-contained ManageWaitingList() function and move it to any project with minimal tweaking to the variables at the top targeting the DOM elements
  • Turn On/Off Easily: Simply run the ManageWaitingList.init() command to initialize the functionality on a particular page
  • Improved Variable Scope: Because all of the variables are defined on block level, within the scope of the main function, there is no chance for variable conflicts with other parts of your code
  • Namespacing: All the code is contained within one namespace ManageWaitingList which will prevent collisions
  • Little Bit of ES6: By using the ES6 variable declaration const for the main function, we prevent any conflict there as well

Here’s a great article on namespacing in JavaScript.

The Code

Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Leave a Reply