Book Image

Mastering JavaScript Design Patterns

By : Simon Timms
Book Image

Mastering JavaScript Design Patterns

By: Simon Timms

Overview of this book

Table of Contents (5 chapters)

The road to JavaScript

We'll never know how language first came into being. Did it slowly evolve from a series of grunts and guttural sounds made during grooming rituals? Perhaps it developed to allow mothers and their offsprings to communicate. Both of these are theories, all but impossible to prove. Nobody was around to observe our ancestors during that important period. In fact, the general lack of empirical evidence lead the Linguistic Society of Paris to ban further discussions on the topic, seeing it as unsuitable for serious study.

The early days

Fortunately, programming languages have developed in recent history and we've been able to watch them grow and change. JavaScript has one of the more interesting histories in modern programming languages. During what must have been an absolutely frantic 10 days in May of 1995, a programmer at Netscape wrote the foundation for what would grow up to be modern JavaScript.

At that time, Netscape was involved in the first of the browser wars with Microsoft. The vision for Netscape was far grander than simply developing a browser. They wanted to create an entire distributed operating system making use of Sun Microsystems' recently released Java programming language. Java was a much more modern alternative to C++ that Microsoft was pushing. However, Netscape didn't have an answer to Visual Basic. Visual Basic was an easier to use programming language, which was targeted at developers with less experience. It avoided some of the difficulties around memory management which makes C and C++ notoriously difficult to program. Visual Basic also avoided strict typing and overall allowed more leeway.

Brendan Eich was tasked with developing Netscape repartee to VB. The project was initially codenamed Mocha but was renamed LiveScript before Netscape 2.0 beta was released. By the time the full release was available, Mocha/LiveScript had been renamed JavaScript to tie it into the Java applet integration. Java applets were small applications that ran on the browser. They had a different security model from the browser itself and so were limited in how they could interact with both the browser and the local system. It is quite rare to see applets these days, as much of their functionality has become part of the browser. Java was riding a popular wave at that time and any relationship to it was played up.

The name has caused much confusion over the years. JavaScript is a very different language from Java. JavaScript is an interpreted language with loose typing that runs primarily on the browser. Java is a language that is compiled to bytecode, which is then executed on the Java Virtual Machine. It has applicability in numerous scenarios from the browser (through the use of Java applets) to the server (Tomcat, JBoss, and so on) to full desktop applications (Eclipse, OpenOffice). In most laypeople's minds, the confusion remains.

JavaScript turned out to be really quite useful for interacting with the web browser. It was not long until Microsoft had also adopted JavaScript in their Internet Explorer to complement VBScript. The Microsoft implementation was known as JScript.

By late 1996, it was clear that JavaScript was going to be the winning web language for the near future. In order to limit the amount of language deviation between implementations, Sun and Netscape began working with the European Computer Manufacturers Association (ECMA) to develop a standard to which future versions of JavaScript would need to comply. The standard was released very quickly (very quickly in terms of how rapidly standard organizations move) in July of 1997. On the off chance that you have not seen enough names yet for JavaScript, the standard version was called ECMAScript, a name which still persists in some circles.

Unfortunately, the standard only specified the very core parts of JavaScript. With the browser wars raging, it was apparent that any vendor that stuck with only the basic implementation of JavaScript would quickly be left behind. At the same time, there was much work going on to establish a standard document object model (DOM) for browsers. The DOM was, in effect, an API for a web page that could be manipulated using JavaScript.

For many years, every JavaScript script would start by attempting to determine the browser on which it was running. This would dictate how to address elements in the DOM, as there were dramatic deviations between each browser. The spaghetti of code that was required to perform simple actions was legendary. I remember reading a year-long 20 part series on developing Dynamic HTML (DHTML) drop-down menus such that they would work on both Internet Explorer and Netscape Navigator. The same functionality can now be achieved with pure CSS without even having to resort to JavaScript.


DHTML was a popular term in the late 1990s and early 2000s. It really referred to any web page that had some sort of dynamic content that was executed on the client side. It has fallen out of use as the popularity of JavaScript has made almost every page a dynamic one.

Fortunately, the efforts to standardize JavaScript continued behind the scenes. Versions 2 and 3 of ECMAScript were released in 1998 and 1999. It looked like there might finally be some agreement between the various parties interested in JavaScript. Work began in early 2000 on ECMAScript 4, which was to be a major new release.

A pause

Then, disaster struck! The various groups involved in the ECMAScript effort had major disagreements about the direction JavaScript was to take. Microsoft seemed to have lost interest in the standardization effort. It was somewhat understandable as it was around that time that Netscape self-destructed and Internet Explorer became the de facto standard. Microsoft implemented parts of ECMAScript 4 but not all of it. Others implemented more fully featured support but, without the market leader on board, developers didn't bother using them.

Years passed without consensus and without a new release of ECMAScript. However, as frequently happens, the evolution of the Internet could not be stopped by a lack of agreement between major players. Libraries such as jQuery, Prototype, Dojo, and MooTools papered over the major differences in browsers, making cross-browser development far easier. At the same time, the amount of JavaScript used in applications increased dramatically.

The way of Gmail

The turning point was, perhaps, the release of Google's Gmail application in 2004. Although XMLHttpRequest, the technology behind Asynchronous JavaScript and XML (AJAX), had been around for about 5 years when Gmail was released, it had not been well used. When Gmail was released, I was totally knocked off my feet by how smooth it was. We've grown used to applications that avoid full reloads, but at that time it was a revolution. To make applications like that work, a great deal of JavaScript is needed.


AJAX is a method by which small chunks of data are retrieved from the server by a client instead of refreshing the entire page. The technology allows for more interactive pages that avoid the jolt of full page reloads.

The popularity of Gmail was the trigger for a change that had been brewing for a while. Increasing JavaScript acceptance and standardization pushed us past the tipping point for the acceptance of JavaScript as a proper language. Up until that point, much of the use of JavaScript was for performing minor changes to the page and for validating form input. I joke with people that in the early days of JavaScript the only function name that was used was Validate().

Applications such as Gmail that have a heavy reliance on AJAX and avoid full-page reloads are known as single page applications (SPAs). By minimizing the changes to the page contents, users have a more fluid experience. By transferring only JavaScript Object Notation (JSON) payload, instead of HTML, the amount of bandwidth required is also minimized. This makes applications appear to be snappier. In recent years, there have been great advances in frameworks that ease the creation of SPAs. AngularJS, Backbone.js, and Ember.js are all Model View Controller style frameworks. They have gained great popularity in the past two to three years and provide some interesting use of patterns. These frameworks are the evolution of years of experimentation with JavaScript best practices by some very smart people.


JSON is a human readable serialization format for JavaScript. It has become very popular in recent years as it is easier and less cumbersome than previously popular formats such as XML. It lacks many of the companion technologies and strict grammatical rules of XML, but makes up for it with simplicity.

At the same time as the frameworks using JavaScript are evolving, the language is too. A much vaunted new version of JavaScript has been under development for some years. ECMAScript 6 will bring some great improvements to the ecosystem. A number of other languages that transcompile to JavaScript are also gaining popularity. CoffeeScript is a Python-like language that strives to improve the readability and brevity of JavaScript. Developed by Google, Dart is being pushed by Google as an eventual replacement for JavaScript. Its construction addresses some of the optimizations that are impossible in traditional JavaScript. Until a Dart runtime is sufficiently popular, Google provides a Dart to JavaScript transcompiler. TypeScript is a Microsoft project that adds some ECMAScript 6 syntax as well as an interesting typing system to JavaScript. It aims to address some of the issues that large JavaScript projects present.

You can see the growth of JavaScript in the following timeline:

The way of Gmail

The point of this discussion about the history of JavaScript is twofold: first it is important to remember that languages do not develop in a vacuum. Both human languages and computer programming languages mutate based on the environments in which they are used. It is a popularly held belief that the Inuit people have a great number of words for "snow" as it was so prevalent in their environment. This may or may not be true depending on your definition for the word and exactly who makes up the Inuit people. There are, however, a great number of examples of domain-specific lexicons evolving to meet the requirements for exact definitions in narrow fields. One need look no further than a specialty cooking store to see the great number of variants of items which a layperson, such as me, would call a pan.

The Sapir–Whorf hypothesis is a hypothesis within the linguistics domain that suggests that not only is language influenced by the environment in which it is used but also that language influences its environment. Also known as linguistic relativity, the theory is that one's cognitive processes differ based on how the language is constructed. Cognitive psychologist Keith Chen has proposed a fascinating example of this. In a very highly viewed TED talk, Dr. Chen suggested that there is a strong positive correlation between languages that lack a future tense and those that have high saving rates ( The hypothesis at which Dr. Chen arrived is that when your language does not have a strong sense of connection between the present and the future, it leads to more reckless behavior in the present.

Thus, understanding the history of JavaScript puts one in a better position to understand how and where to make use of JavaScript.

The second reason I explored the history of JavaScript is because it is absolutely fascinating to see how quickly such a popular tool has evolved. At the time of this writing, it has been less than 20 years since JavaScript was first built and its rise to popularity has been explosive. What is more exciting than to work in an ever evolving language?

JavaScript everywhere

Since the Gmail revolution, JavaScript has grown immensely. The renewed browser wars, which pit Internet Explorer against Chrome against Firefox, have lead to building a number of very fast JavaScript interpreters. Brand new optimization techniques have been deployed and it is not unusual to see JavaScript compiled to machine native code for the added performance it gains. However, as the speed of JavaScript has increased, so has the complexity of the applications built using it.

JavaScript is no longer simply a language for manipulating the browser either. The JavaScript engine behind the popular Chrome browser has been extracted and is now at the heart of a number of interesting projects such as Node.js. Node.js started off as a highly asynchronous method of writing server-side applications. It has grown greatly and has a very active community supporting it. A wide variety of applications have been built using the Node.js runtime. Everything from build tools to editors have been built on the base of Node.js.

JavaScript can even be used to control microcontrollers. The Johnny-Five framework is a programming framework for the very popular Arduino. It brings a much simpler approach to programming the devices than the traditional low-level languages used for programming these devices. Using JavaScript and Arduino opens up a world of possibilities, from building robots to interacting with real-world sensors.

All of the major smartphone platforms (iOS, Android, and Windows Phone) have an option to build applications using JavaScript. The tablet space is much the same, with tablets supporting programming using JavaScript. Even the latest version of Windows provides a mechanism for building applications using JavaScript. JavaScript is used everywhere, as shown in the following diagram:

JavaScript everywhere

JavaScript is becoming one of the most important languages in the world. Although language usage statistics are notoriously difficult to calculate, every single source that attempts to develop a ranking puts JavaScript in the top 10:

Language index

Rank of JavaScript






What is more interesting is that each one of these rankings suggests that the usage of JavaScript popularity is on the rise.

The long and short of it is that JavaScript is going to be a major language in the next few years. More and more applications are being written in JavaScript and it is the lingua franca for any sort of web development. The developer of the popular Stack Overflow website, Jeff Atwood, created Atwood's Law regarding the wide adoption of JavaScript:

Any application that can be written in JavaScript, will eventually be written in JavaScript.

This insight has been proven to be correct time and time again. There are now compilers, spreadsheets, word processors—you name it—all written in JavaScript.

As the applications that make use of JavaScript increase in complexity, the developers stumble upon many of the same issues as have been encountered in traditional programming languages: How can we write this application to be adaptable to change?

This brings us to the need for properly designing applications. No longer can we simply throw a bunch of JavaScript into a file and hope that it works properly. Nor can we rely on libraries such as jQuery to save ourselves. Libraries can only provide additional functionality, and they contribute nothing to the structure of an application. At least some attention must now be paid to how to construct the application to be extensible and adaptable. The real world is ever changing and any application that is unable to change to suit the changing world is likely to be left in the dust. Design patterns provide some guidance in building adaptable applications, which can shift with changing business needs.