This post will discuss possible ways to implement the singleton pattern in JavaScript.

The singleton pattern is a design pattern that ensures that only one instance of a class or an object exists in the application. It can be useful for managing global state, sharing resources, or implementing caching, or coordinating system-wide actions. There are different ways to implement the singleton pattern in JavaScript, but one common function is to use an immediately invoked function expression (IIFE) that returns an object with a getInstance() function. The getInstance() function checks if an instance already exists; if not, it creates one and stores it in a private variable. Then, it returns the instance to the caller.

1. Using a function expression

One way is to use a function expression and an immediately invoked function expression (IIFE) to create a private scope and return the singleton instance. This way, we can use closures to encapsulate the instance and prevent it from being modified or accessed from outside. Here’s an example of how we can achieve this:

Download  Run Code

2. Using a class expression

Another way is to use a class expression and a static property to store and access the singleton instance. This way, we can use the class syntax to define the constructor and the functions of the singleton, and use the static keyword to ensure that only one instance is created and shared. Here’s an example of how we can achieve this:

Download  Run Code

3. Using an object literal

A third way is to use an object literal and the Object.freeze() function to create and protect the singleton instance. This way, we can use a simple object notation to define the properties and functions of the singleton, and use the Object.freeze() function to prevent any modification or addition of new properties. Here’s an example of how we can achieve this:

Download  Run Code

That’s all about singleton pattern implementation in JavaScript.