Tutorial

How To Work With Singletons in JavaScript

Updated on December 28, 2020
authorauthor

Vijay Prasanna and Ceora Ford

How To Work With Singletons in JavaScript

Introduction

The singleton is one of the most well-known design patterns. There are times when you need to have only one instance of a class and no more than that. This one class could be some kind of resource manager or some global lookup for values. This is where singletons come in.

In this article, you will take a look at what singletons are and how to best implement them in JavaScript.

Prerequisites

To successfully complete this tutorial, you will need the following:

Understanding Singletons

Singletons are used to create an instance of a class if it does not exist or else return the reference of the existing one. This means that singletons are created exactly once during the runtime of the application in the global scope.

Based on this definition, singletons seem very similar to global variables. You might be wondering why singletons should be used in a coding language with global variables. There are a few things that make singletons different from global variables:

  • Global variables are lexically scoped whereas singletons are not. This means that if there is another variable with the same name as the global variable inside a programming block, then the first reference is given priority. Singletons, however, should not have that reference re-declared.
  • The value of a singleton is modified through methods.
  • The singleton is not freed until the termination of the program, which is likely not the case for a global variable.

Even in a language that supports global variables, singletons can be very useful. There are scenarios where singletons are handy. Some applications of singletons are logger objects or configuration settings classes.

Declaring Singletons

There are several ways to declare a singleton. This is one format you might see:

var SingletonInstance = {
 method1: function () { ... }
 method2: function () { ... }
};

This singleton would be logged to the console like this:

console.log(SingletonInstance.method1());
console.log(SingletonInstance.method2());

It’s good to keep in mind that this is not the best way to declare singletons. Another way would be to use a factory class that creates a singleton once.

var SingletonFactory = (function(){
  function SingletonClass() {
    // ...
  }

  var instance;

  return {
    getInstance: function(){
      if (!instance) {
        instance = new SingletonClass();
        delete instance.constructor;
      }
      return instance;
    }
  };
})();

This is a better alternative to the first example because the class definition is private and the constructor is deleted after the first instance creation. This will prevent duplicate singletons from being created in the program. The drawback to this approach is that it’s very similar to the factory pattern.

There is still a third approach. This approach implements a combination of ES6 classes and the Object.freeze() method:

script.js
class Singleton {
  constructor() {
   // ...
  }

  method1() {
    // ...
  }

  method2() {
    // ...
  }
}

const singletonInstance = new Singleton();

Object.freeze(singletonInstance);

The Object.freeze() method prevents modification to properties and values of an object. So applying Object.freeze() to singletonInstance means you will not be able to change any of its properties or values later on in your code.

You can go further and write this singleton as a module and export it with the ES6 export functionality:

script.js
export default singletonInstance;

Then this singleton could be used in a separate file by importing it:

otherFile.js
import mySingleton from './script.js';

mySingleton.method1();

With these three approaches to creating singletons, choose which method fits best with your specific use case that allows for high readability.

Conclusion

It’s not always necessary to use singletons in your JavaScript code. Use singletons where it doesn’t affect the state of the application. This constraint severely limits their usage in big applications.

With this fundamental design pattern in your tool kit, you may want to explore factory patterns in JavaScript. If you’re interested in learning more about state management, check out these articles on state management in React with Redux and state management with React hooks.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Vijay Prasanna

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
2 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

“It’s good to keep in mind that this is not the best way to declare singletons.”

Why? I really don’t like stating an opinion in an article like this and providing 0 arguments for backing it up.

That was quite tasteful information. That helped me to understand the singleton pattern. Thanks

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more