Singleton in JavaScript

Wikipedia describes the singleton design pattern as:

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.



Singleton is one of the most well known and also hated design patterns, all the time. It is very easy to implement a basic version of the singleton pattern so that’s the reason it is that well known. But if we look deeper into different details, there are plenty of problems, which may happen because of poor implementation:

  • Instantiating multiple singletons because of concurrent access to the getInstance method of the singleton.
  • Instantiating multiple singletons because of serialization/deserialization
  • Inheriting from a singleton object
  • etc…

Thanks God we don’t have to consider all these corner cases in JavaScript.

The simplest singleton implementation in JavaScript is:

And yes – this is singleton!

Addy Osmani suggests the following implementation at his book “Learning JavaScript Design Patterns”:

This implementation is based on the module pattern. The module pattern is applied two times – the first application aims to provide the actual singleton and keeps the private data/behavior inside a closure. The second usage of the module pattern aims to provide the public interface used for getting the singleton object, which is kept inside a closure.

It is absolutely valid and useful implementation:

  • It instantiates only a single object
  • It is safe – it keeps the reference to the singleton inside a variable, which lives inside a lexical closure, so it is not accessible by the outside world
  • It allows privacy – you can define all private methods of your singleton inside the lexical closure of the first module pattern

As drawback I can point the lack of specific “type” of the singleton (i.e. more specific than object), which won’t allow you to use the operator instanceof. I can argue that the definition of the private members can lead to poor unit testing, but if they are private, they are not intended for testing anyway.

Another implementation of singleton, which I found in the network is “The best Singleton pattern”:

Here are the main advantages of this implementation:

  • It instantiates only a single object
  • You can use the instanceof operator

As drawback I can state the fact that you can easy change the prototype property _singletonInstance of your singleton. This way, when MySingleton is called once again, it will create a new object:

Implementation I use is formed by combining both approaches from above:

In this example we use the module pattern once again, in order to enclose the singleton implementation into a lexical closure and provide a public interface for getting its instance.

Sometimes you need to pass arguments when initializing a singleton for first time. This is easy achieved using the method init. The init method is not aware of the arguments required by the singleton – all it does is to forward the call to the internal MySingleton function with context null. Inside the implementation of the MySingleton constructor function we make a check whether the current context – this is of type MySingleton, if it isn’t, then this means that MySingleton is not called with the new operator, so we recursively call new MySingleton with the required parameters.

What are the benefits we get from this implementation:

  • It instantiates only a single object
  • It is safe – it keeps the reference to the singleton inside a variable, which lives inside a lexical closure and is not accessible by the outside world
  • It allows you to initialize the singleton with some arguments. The module pattern, which wraps the singleton is not aware of the initialization arguments – it simply forwards the call with apply
  • You can use the instanceof operator

As drawback, I can state that I feel unnatural for this implementation to use “private” data/behavior – but yes, it is possible if you define them in the lexical closure of the module pattern.

Express over HTTPS

Sometimes you want to test your application in environment closer to the real world. In such cases you might need to run it over TLS.

Here are two simple steps, which can be used to achieve this result:

  1. Generate self-signed certificate

    If you don’t already have certificate you need to generate one:

    You will be asked a couple of questions…
    Certificate generation
    In this case we generated a self-signed certificate for 365 days.

  2. Use Express with HTTPS

    This script will create Express application running over HTTPs.
    Run the application:

    Enter the passphrase you entered during the creation of the certificate…

    Now open your browser: https://localhost:55555/.
    After trusting the certificate you’d be done!

    Https with Express

What I get from the JavaScript MV* frameworks

Why should I use JavaScript MVC, MVVM, MVP or simply MVW(hatever works for you)?

When I talk with people, who are beginners/intermediate in JavaScript I’m often asked this question. They are usually people who, until now, have used JavaScript only for making their website “fancier” – adding client-side form validation, creating carousel, checking whether a user already exists with simple Ajax request. When you start building something bigger (+10k lines of JavaScript) I truly believe that there are a few benefits from using such micro-architectural frameworks.


Each of the frameworks provides you two types of code reuse:


Alright, jQuery takes care of some boilerplates as well, but these boilerplates are usually DOM/Ajax oriented. There’s nothing in the core of jQuery, which provides you two-way data-binding, for example. When you develop Single-Page web application you see that there are a lot of cases where you need to explicitly set the content of given DOM elements, or recompile template when some data changes. Frameworks like Ember.js and AngularJS do this for you!

Reuse of your own code

You have out-of-the-box Separation of Concerns. In each MV* framework you have Model and View. They both have their own responsibilities – the model is responsible for encapsulating your domain specific models (in case of twitter – Tweet, User), on the other hand the view is responsible for showing the model (and eventually handling events, it depends on the framework). This means that your model is not coupled with its representation and eventually can be easily reuse it in different project. In this type of code reuse, usually you cannot reuse as much source code, across your projects, as in the case of boilerplates but you still have it, without any extra work.

Level of abstraction

Each framework provides you a higher level of abstraction, which allows you to handle more complex applications. Try to build something large without any framework and you will find yourself dividing the code into different coherent modules, trying to decouple them as much as possible. Probably you will end up with something like this module architecture. Of course, if you don’t follow any guidelines for good OO design (explicitly or implicitly), it is very likely to end up with large bunch of spaghetti.


Most of the MV* frameworks are build with testing in mind. For example, in AngularJS you have Dependency Injection, which allows you to mock given service quite easily. You don’t need monkey patching anymore! One of the drawbacks of the module architecture, which was referred above, is its hard testability.

Implicit conventions

JavaScript is weird. It doesn’t tell you how you should write your code. You can use functional style, procedural style, OO style. There’s a lack of many of the tools available in languages like Java and C#. You don’t have namespaces, you even don’t have a single way for creating objects. You can create object by using the object literal:

or the module pattern

or constructor function

…If you have team with 15 JavaScript developers and each of them has his own opinion how JavaScript should be used you are in big troubles. MV* frameworks give you strict guidelines for how you should organize your code. Each of the developers will be forced to use “the Angular way”, “the Backbone way”, or whatever way your project uses.


Why not to create a custom framework and build my applications with it? First, you already have pretty good solutions, which are build by great developers and tested by hundreds others. Second, if your team is dynamic you will increase the learning curve for the new developers who are joining your team. Each of them should spend time studying your problem domain, your proprietary framework and your existing code base.

1.61803399 == 42 //!!!