Create Singleton Object in JavaScript

Saqib Ullah Siddiqui
2 min readJun 29, 2022

--

Do we need patterns? Yes, off-course good programmers always prefer to use design patterns in their daily coding.

Today we are going to see how to implement the singleton pattern in JavaScript. To get a basic understanding of patterns, I would recommend to please read design patterns first. Let me clear one thing here design patterns are languages independent, commonly speaking it’s a solution to daily occurring coding problems.

With the help of this design pattern, we eliminate the need for a global variable in the program.

Let’s build a very simple class called Rectangle, what we are assuming here our application needs Rectangle objects of the same size in different locations. If you read the class constructor it always takes input parameters e.g. height and width and calculates the total area of the shape.

To achieve the singleton design pattern we create another object with the name “Singleton” as an immediate anonymous function. To understand what is IIFE please visit this link.

To test the singleton object we created an execute() function, in which we create two different objects with different parameters using Singleton getInstance function. As we already know the singleton pattern helps us return a single instance with global access points. Another very important point that we need to focus on is line no’s 45 instance1 === instance2 code. When you execute this piece of code it always returns “true”, because when the second time getInstance function executes it first checks the instance variable, if it’s null then create a new Rectangle type object using createInstance otherwise return the existing object.

Common Usage

In general singleton pattern will be implemented in the following cases

  1. Database connection
  2. Application logger or logger
  3. Configuration management

I hope this blog will help you to understand the most common design pattern of programming.

Thanks!

--

--

Saqib Ullah Siddiqui
Saqib Ullah Siddiqui

Written by Saqib Ullah Siddiqui

I read to know, I write to recall.

No responses yet