0
0
JavascriptConceptBeginner · 3 min read

Singleton Pattern in JavaScript: What It Is and How It Works

The singleton pattern in JavaScript is a design approach that ensures a class or object has only one instance throughout the program. It provides a single point of access to that instance, preventing multiple copies and helping manage shared resources.
⚙️

How It Works

The singleton pattern works like a single shared tool in a workshop that everyone uses instead of having many copies. When you ask for this tool, you always get the same one, so it keeps things organized and consistent.

In JavaScript, this means creating an object or class that controls its own instance. When you try to create a new instance, it checks if one already exists and returns that instead of making a new one. This way, the program uses only one instance, saving memory and avoiding conflicts.

💻

Example

This example shows a simple singleton object that stores a count. No matter how many times you get the instance, it always refers to the same object.

javascript
const Singleton = (function() {
  let instance;

  function createInstance() {
    return { count: 0 };
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const obj1 = Singleton.getInstance();
const obj2 = Singleton.getInstance();
obj1.count++;
console.log(obj2.count);
Output
1
🎯

When to Use

Use the singleton pattern when you need to make sure only one object controls a resource or service, like a database connection, configuration settings, or logging system. This avoids confusion and keeps data consistent.

For example, if your app needs to log messages, having one logger instance prevents multiple files or formats. Or if you connect to a database, one connection object can be shared safely.

Key Points

  • Singleton ensures only one instance exists.
  • It provides a global access point to that instance.
  • Helps manage shared resources safely.
  • Common in configuration, logging, and database connections.

Key Takeaways

Singleton pattern restricts a class to a single instance in JavaScript.
It provides a controlled global access point to that instance.
Use it to manage shared resources like configurations or connections.
It helps keep your program organized and consistent.
The pattern avoids unnecessary duplication and saves memory.