I was involved in a discussion with another developer and the topic of patterns came up. To quote Addy Osmani:

Design patterns...provide us a common vocabulary to describe solutions.

The discussion grew out of the existence of a line of JavaScript code in an application.

var variable = variable == undefined ? 'value' : variable;  

While that line of code is completely functional and does provide the intended solution of supplying a default value to a variable if it doesn't have one, it isn't as clear as a JavaScript developer would expect. ...and by not being clear it could cause a derailment of thought as the line is understood.

So how would a JavaScript developer expect to see that line?

var variable = variable || 'value';  

In short, variable || 'value' will return variable if variable is true, otherwise it defaults to 'value'. A developer coming later would instantly recognize that pattern and understand that it is only assigning a default value to an undefined variable.

It is also true that a developer that is well versed in the library of patterns will spend less time considering solutions. Instead of spending time thinking about forming the code to solve the problem, the pattern can be written very quickly, almost as though coming from muscle memory!

From the simple to the advanced

Now admittedly that line of code is a very simple example of a design pattern, and there exists a rather lengthy list of JavaScript design patterns:

  • Module pattern
  • Revealing module pattern
  • Observer pattern
  • Mediator pattern
  • etc, etc, etc

All of these patterns help to solve common programming problems, while also making your code much more familar and readable to developers coming after you.

Resources

Addy Osmani's book Learning JavaScript Design Patterns is a fantastic place to begin your exploration and study of common patterns.

Addy isn't the only one of course to have written about patterns and a simple Google search will reveal several pages of results, the number being an indication of just how important this topic is to learn.