Module Pattern with example: Essential JavaScript Concepts

1 minute read

In our previous video session JavaScript Concepts- Module Pattern | 0004-11 we have learnt about basics of Module Pattern. Here in this video tutorial JavaScript Concepts- Module Pattern example with Logger Object | 0004-12 we will understand working of module pattern with help of practical examples. Basically there are three ways to create a class:

  • Prototype pattern
  • Regular Class
  • Module pattern (Revealing Pattern).

We will discuss Prototype pattern in our subsequent video sessions, let’s discuss other two types here. In Regular Class we can write constructor function (Any function who gives us instance is known as constructor function), with this we can create Private function rather than exposing small functions, instead can expose API’s. But issue here is we end up creating new instances. What if we want to stop people from creating multiple instances?

So here comes the concept of Module Pattern which restricts people to create instances. Through module pattern we get many benefits like we can create private function, public function, it also guarantees we have one instance only and it is memory efficient as well.

Let’s understand this with Logger example. Here in JS, in order to create a class or Object we will use function as it is the first class citizen in JS. It is explained in detail in our video session JavaScript Concepts- Module Pattern example with Logger Object | 0004-12. It also demonstrates Closure concept of JavaScript.

Module pattern is heavily designed on closure principle; whoever is familiar with Closure concept can design this. This is very important designing pattern as it fulfills any kind of requirement which needs single instance. We can design very complicated objects like we can have private variables; private functions and has flexibility to expose whatever we want to. It is good for services and testing/TDD as well.

Our next video tutorial JavaScript Concepts- Module Pattern & How to use It in App | 0004-13 Explains how to use Module pattern in App. Please find code snippet from our GitHub code base below:

Hiring Guide For Node.js developers

Hiring Guide for Node.JS Developer

Subscribe to Full Stack Master