JavaScript Design Patterns: The Singleton

Among languages used in widespread production, JavaScript is by far the most quickly evolving, looking less like its earliest iterations and more like Python with every new spec put forth by ECMA International. While the changes have their fair share of detractors, the new JavaScript does succeed in making code easier to read and reason about, easier to write in a way that adheres to software engineering best practices (particularly the concepts of modularity and SOLID principles), and easier to assemble into canonical software design patterns. Let’s dig into that last point by examining how the best way to implement a singleton in JavaScript has evolved with the rise of ES6.

What Is ES6

ES6 (aka ES2015) is the latest specification of the JavaScript language, and the first major update to the language since ES5 was standardized in 2009. Browser support for ES6 is still incomplete, however, ES6 code can easily be transpiled into ES5 code using a tool such as Babel. ES6 gives JavaScript a ton of new features, including a superior syntax for classes, and new keywords for variable declarations. You can learn more about it by perusing Sitepoint articles on the subject.

What Is a Singleton

alt text

In case you’re unfamiliar with the singleton pattern, it is, at its core, a design pattern that restricts the instantiation of a class to one object. Usually, the goal is to manage global application state. Some examples I have seen or written myself in real software development life include using a singleton as the source of config settings for a web app, on the client-side for anything initiated with an API key (you usually don’t want to risk sending multiple analytics tracking calls, for example), and to store data in memory in a client-side web application (e.g. stores in Flux).

A singleton should be immutable by consuming code, and there should be no danger of instantiating more than one of them.

Note: there are scenarios when singletons might be bad, and arguments that they are, in fact, always bad. For that discussion, you can check out this helpful article on the subject.

The Old Way of Creating a Singleton in JavaScript

The old way of writing a singleton in JavaScript involves leveraging closures and immediately-invoked function expressions . Here is how we might write a (very simple) store for a hypothetical Flux implementation the old way:

Continue reading %JavaScript Design Patterns: The Singleton%

Source: Sitepoint