SHARE
Facebook X Pinterest WhatsApp

Implementing the Singleton Design Pattern in JavaScript

Jul 10, 2017

When working in applications, it is imperative that you design solutions that are maintainable and the code is readable. You should be able to find out the recurring problems in designs and then adopt a strategy to mitigate them. This way, you can write much clean, better and maintainable code. This is exactly where design patterns come to play.

Design patterns provide solutions to problems that occur often in software engineering. Such solutions are proven and time-tested. The Singleton design pattern is a Gang of Four (GOF) design pattern. It falls under the “creational design pattern” category. Creational design patterns are those that deal with object creation. There are two other categories of GOF design patterns, namely, structural patterns and behavioral patterns.

In this series of articles, we will implement the GOF design patterns using JavaScript. Incidentally, JavaScript is a dynamic, weakly-typed scripting language that provides support for many of the OOP features. This article, the first part in this series of articles on design patterns, presents a discussion on how we can implement the Singleton design pattern using JavaScript.

What is the Singleton design pattern?

The Singleton design pattern is a creational pattern that states that one and only one instance of a class would persist in the memory during the application’s life cycle. In other words, this design pattern restricts instantiation of a class to just one object. As far as JavaScript is concerned, a singleton is an instance that is created just once — any repeated calls to the constructor would always fetch the same instance.

Implementing the Singleton pattern

An easy way to implement the Singleton design pattern in JavaScript is by using an object literal as shown below.

var singleton = {
  method1: function () {
    //Write your usual code here
     },
     method2: function () {
     //Write your usual code here 
     }
};

Here’s is another code snippet that illustrates how you can implement the Singleton pattern in JavaScript.

var Singleton = (function(){
    function Singleton() {
        //Write your usual code here
    }
    var instance;
    return {
        getInstance: function(){
            if (null == instance) {
                instance = new Singleton();               
                instance.constructor = null; // Note how the constructor is hidden to prevent instantiation
            }
            return instance; //return the singleton instance
        }
   };
})();

Refer to the code snippet given above. Note how a check is made to see if the instance is null. If the instance is null, a new instance is created and returned by suppressing/hiding the constructor. If the instance is non-null, the instance is returned. This approach is also known as the module pattern. As you can see, you can encapsulate the private members that belong to a particular instance using closures.

Now that we have implemented our Singleton class, the following code snippet can be used to invoke the function.

var justOneInstance = Singleton.getInstance();

The GOF states: “The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton. Singletons are useful in situations where system-wide actions need to be coordinated from a single central place. An example is a database connection pool. The pool manages the creation, destruction, and lifetime of all database connections for the entire application ensuring that no connections are ‘lost’.”

Summary This article presented a discussion on the Singleton design pattern, why it is useful and how it can be implemented in JavaScript with code examples wherever appropriate. In future articles in this series, we will explore the other design patterns and examine how they can be implemented in JavaScript. Happy reading!

Reference

JavaScript Patterns: Build Better Applications with Coding and Design Patterns – by Stoyan Stefanov

Recommended for you...

The Revolutionary ES6 Rest and Spread Operators
Rob Gravelle
Aug 23, 2022
Ahead of Time (AOT) Compilation in Angular
Tariq Siddiqui
Aug 16, 2022
Converting a JavaScript Object to a String
Rob Gravelle
Aug 14, 2022
Understanding Primitive Type Coercion in JavaScript
Rob Gravelle
Jul 28, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.