Skip to main content

Singleton Pattern in JavaScript (Live Playground)

The Singleton pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to that instance. In this tutorial, we'll explore the Singleton pattern in JavaScript, including its use cases, implementation, and benefits.

Why Use the Singleton Pattern?

The Singleton pattern is particularly useful when you need to control access to shared resources, manage application-wide state, or ensure that specific objects have a single instance.

Some common use cases include:

  1. Database connections: Ensuring that your application has only one active connection to the database at a time.
  2. Configuration data: Centralizing access to configuration settings used throughout the application.
  3. Logging: Creating a single logging object that can be accessed from any part of the application.

Implementing the Singleton Pattern in JavaScript

Here's an example of how to implement the Singleton pattern using a JavaScript class:

TypeScript
class Singleton {
static instance;

constructor() {
if (Singleton.instance) {
return Singleton.instance;
}

Singleton.instance = this;
}

doSomething() {
console.log('Performing an action...');
}
}

const instance1 = new Singleton();
const instance2 = new Singleton();

console.log(instance1 === instance2); // Output: true

In this example, the Singleton class uses a static property instance to store its unique instance. The constructor checks if an instance already exists, and if so, returns the existing instance. If not, it creates a new instance and stores it in the instance property.

Live Playground, Try it Yourself

Benefits of the Singleton Pattern

Implementing the Singleton pattern in your JavaScript projects offers several benefits:

  1. Controlled Access: The Singleton pattern provides a single point of access to a shared resource, making it easier to manage and control.
  2. Reduced Resource Usage: By ensuring only one instance of a class, the Singleton pattern helps minimize the consumption of system resources.
  3. Consistency: The Singleton pattern ensures that all parts of the application share the same instance of a class, promoting consistency in behavior and state management.

Conclusion

In summary, the Singleton pattern is a valuable tool in JavaScript development that can help you manage shared resources and maintain application-wide state efficiently. By understanding and implementing this pattern, you can enhance the quality and maintainability of your code.