Apart from apparently being a brand of whisky, Singleton is a pattern that restricts instantiation of a class to a single object. One of the most common patterns in programming, in Javascript it is commonly used for storing state between different modules, always returning the same object you modified somewhere else.

For example, Angular services and factories are singletons. And chances are if you ever used a framework, u came across this design pattern.

One of the benefits is that singletons are usually lazily instantiated, meaning that a singleton is not created until it is needed for the first time.

If you find yourself needing to much singletons, it probably means that your logic is to tightly coupled, and you should consider revisiting your design choices, but for some sweet spots, such as say a data service, this design is irreplaceable. Say you have a page that consists of many different modules all querying your RESTfull API, and you want to show a loader when there is a request pending, or hide it when all the requests have finished loading.

There are many ways to accomplish this, so let’s try a few.

There is another sweet method of achieving this, and it is called self defining function.  As it’s name states, this function overwrites its self but retains all the data provided in the first initialization in a closure.

And there it is! There are numerous other ways you could construct a singleton in Javascript, so go ahead and hit those google queries!