Open In App

What is Singleton Design Pattern in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Singleton Design Pattern in JavaScript is a creational pattern that ensures a class has only one instance and provides a global point of access to that instance. This pattern is particularly useful when a single object needs to coordinate actions across the system, such as managing a global configuration or controlling access to a shared resource.

In a Singleton pattern, a class is responsible for creating its instance if one does not already exist and providing a mechanism for accessing that instance globally. The pattern typically involves defining a static method or property within the class that ensures only one instance is created and returned.

Example: To demonstrate singleton design pattern in JavaScript.

Javascript




class SingletonInJS {
  constructor() {
    if (!SingletonInJS.instance) {
      SingletonInJS.instance = this;
    }
 
    return SingletonInJS.instance;
  }
}
 
const instance1 = new SingletonInJS();
const instance2 = new SingletonInJS();
 
console.log(instance1 === instance2);


Output

true

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads