javascript-300x120

JavaScript design patterns are, essentially, efficient problem solving strategies. When you build large scale web applications of high complexity, code becomes increasingly difficult to manage and various problems arise throughout the building process. JavaScript design patterns not only provide solutions to these problems but also organize your code in a way that is easy to understand, maintain, scale and share. Design patterns also significantly reduce the size of code files and increase the speed of debugging your application.

This article serves as an introduction to JavaScript design patterns and therefore the explanations and examples are kept simple. For further information and advanced examples please visit the resources provided at the end of the article.

Certain popular patterns have developed over time and are used frequently due to their track record of providing viable solutions in the past. Still, new patterns are developed to overcome new challenges that arise. Following is an introduction to the three categories of JavaScript patterns and examples of each type.

Design Pattern Categories

JavaScript is an object oriented language and the types of JavaScript design patterns mainly revolve around handling objects. JavaScript design patterns are categorized into three different types, namely creational, structural and behavioral. They are used in object creation, overseeing relationships between different objects and organizing object communication. This article illustrates two patterns from each type. Note that there are many more design patterns not covered here.

Creational

Creational design patterns, as the name indicates, are used during object creation. Not all objects are created using this kind of pattern, but they are very suitable for large scale applications. Both creational patterns shown below use the concept of inheritance. Inheritance is a vital characteristic of object oriented programming and essentially means taking something old and adding a new functionality to it, or changing it in some way.

Prototype

The prototype design pattern allows you to create an object without actually creating an object. How is this done? Rather than creating an object from scratch, a new object is created by cloning an existing object. The clone inherits all the properties and methods of the original. However, the clone can redefine or override any property or method it wants. This is all done using prototypes. Every object in JavaScript has a prototype. Objects can inherit properties from their prototype. A prototype can also inherit properties from other object’s prototypes. Because of the way they work, prototypes make it possible to clone one object from another. Consider the code below:

The yorkie object is cloned from the Dog object, meaning yorkie inherits all the properties and methods of dog. However, yorkie is not limited to the properties of dog, and can now define its own properties that are not available in the dog object. Yorkie can also change the properties it wants such as redefining typeBarks as shown above.

Mixin

Mixins act how they sound. They allow you to “mix in” functionalities to other objects. Mixins make it possible to re-use functions throughout your code without having to define the function each time. The code below demonstrates how mixins work.

The example above contains three constructors. There is a constructor for a mixin, an airplane, and a bird. The mixin constructor defines two functions, namely flyUp and flyDown. The airplane and bird constructors have their own functions but can inherit the functions of mixin using the extend statement. Then new instances of airplane and bird can be created which can now use the functions flyUp and flyDown from the mixin constructor.

Structural

Structural design patterns oversee the relationship between objects. One of the main goals of structural design is to ensure that if one part of the program changes, the other parts are not affected by the change and stay the same.

Module

Object oriented programming languages like JavaScript don’t have classes. One of the main advantages of classes is the option of private and public scope. The module pattern mimics this functionality and lets JavaScript objects behave like classes in this regard. Methods and variables can be made public or private within an object. Privacy is achieved using closures. Whatever is inside a closure is private and therefore protected from being accessed by other parts of the program. The following example demonstrates the use of closures.

In the code above countModule is a self-contained module. The variable myCount only exists within the closures of countModule and cannot be accessed from anywhere else. Neither can the function decrementCount be called from any other part of the program as it does not have global scope. The function decrementCount that is inside the module can access the variable myCount.  The variables and functions inside countModule have private scope and cannot be changed by anything outside of it. This is how privacy is established in JavaScript. Notice that there are no explicit declarations of public or private as seen in classes of other languages.

Façade

The façade pattern is aptly named because it produces a façade to users by hiding the inner workings of itself. The public is presented with a simple interface while the complex methods and functionalities are hidden. JavaScript libraries such as jQuery are easy to use because they utilize the façade pattern. Without facades, using some libraries would be more complicated and time consuming. The animate() and css() methods in jQuery are examples of facades.

Behavioral

Behavioral design handles the communication between objects. It is important that the communication between objects is organized, otherwise problems could arise that result in errors that are difficult to find.

Observer

This design pattern involves two components. The subject and a list of observers. Whenever a change occurs in the subject, the list of observers is sent a notification. If a subject doesn’t need a particular observer to be notified it can remove that observer from the list. The methods used in this pattern are publish(data), subscribe(observer) and unsubscribe(observer). Demonstrating these methods are beyond the scope of this introductory article.

Mediator

While the observer pattern is very useful, it can start to create problems if there are too many subjects and observers. In that case, the mediator pattern can be used. The mediator is a single central object that handles all communication between subjects and observers. In the observer pattern several objects could be interacting with each other, however in the mediator pattern all interaction happens through the mediator. The mediator knows what all the other objects are doing and uses this information to make efficient communication decisions between two objects. This makes communication much more organized and prevents errors that occur when there is too much traffic between subjects and observers.

Conclusion

JavaScript design patterns offer a multitude of benefits and are a necessary part of every developer’s toolbox. Design patterns provide rules and structure for code writing that ultimately make applications easier to manage, debug and update. Large applications that do not utilize design patterns may not show problems in the beginning. However, if there is a need to update or scale the code further down the line, it will be an unnecessarily complex task.

Resources

Learning JavaScript Design Patterns

Understanding Design Patterns in JavaScript

Introduction to the JavaScript Module Design Pattern

4 JavaScript Design Patterns You Should Know

Comments

  • daniel morales
    Reply

    Pls, would you mind checking out the var Dog on the first code example. Tks