Singleton Pattern JavaScript

Singleton pattern js

Singleton design pattern in javascript

Definition of Singleton:

Ensure a class has only one instance and provide a global point of access to it.

The Singleton pattern is more popular type of design patterns that restricts instantiation of a class to a single javascript object.
Usually, the Singleton pattern is a class with a special method that creates a new instance of this class if one doesn’t exist in js. If instance already existing, Singleton design pattern simply returns a reference to that object.

In JavaScript, Singletons serve as a dispense resource namespace which isolate implementation javascript code from the global namespace so as to provide one single point of access for functions.

Singleton example in javascript

var mySingleton = (function () {
    var instance;
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            return instance;

// Usage 
    var instance1 = mySingleton.getInstance();
    var instance2 = mySingleton.getInstance();

//check instances
    alert("Same instance? " + (instance1 === instance2));  

The Singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn’t have a name.

The getInstance() method is Singleton’s gatekeeper. This method returns the one and only instance of the object while maintaining a private reference to it which is not accessible to the outside namespace.

The getInstance() method demonstates another design pattern called Lazy Load. It checks if an instance has already been created; if not, it creates one and stores it for future reference. All subsequent calls will receive the stored instance. Lazy loading is a CPU and memory saving technique by creating objects only when absolutely necessary.

Important to note! The difference between a static instance of a class (object) and a Singleton: whilst a Singleton can be implemented as a static instance, it can also be constructed lazily, without the need for resources nor memory until this is actually needed.