Design Patterns in JavaScript

Paul Chien's picture

 The fact that JavaScript is so expressive allows you to be very creative in how design patterns are applied to your code. There are three main reasons why you would want to use design patterns in JavaScript:

  1. Maintainability: Design patterns help to keep your modules more loosely coupled. This makes it easier to refactor your code and swap out different modules. It also makes it easier to work in large teams and to collaborate with other programmers.
  2. Communication: Design patterns provide a common vocabulary for dealing with different types of objects. They give programmers shorthand for describing how their systems work. Instead of long explanations, you can just say, “It uses the factory pattern.” The fact that a particular pattern has a name means you can discuss it at a high level, without having to get into the details.
  3. Performance: Some of the patterns we cover in this book are optimization patterns. They can drastically improve the speed at which your program runs and reduce the amount of code you need to transmit to the client. The flyweight and proxy patterns are the most important examples of this.

There are two reasons why you might not want to use design patterns:

  1. Complexity: Maintainability often comes at a cost, and that cost is that your code may be more complex and less likely to be understood by novice programmers.
  2. Performance: While some patterns improve performance, most of them add a slight performance overhead to your code. Depending on the specific demands of your project, this overhead may range from unnoticeable to completely unacceptable.

Implementing patterns is the easy part; knowing which one to use (and when) is the hard part. Applying design patterns to your code without knowing the specific reasons for doing so can be dangerous. Make an effort to ensure that the pattern you select is the most appropriate and won’t degrade performance below acceptable limits.

[1] Ross Harmes and Dustin Diaz (2008). Pro JavaScript Design Patterns