Helpful JavaScript Design Patterns
So you write JavaScript. That’s pretty much a given for today’s modern web apps. Unfortunately, JavaScript doesn’t always get the organization it deserves and ends up being a procedural mess of jQuery on ready statements.
In this post, I’m going to show you two of my favorite patterns for keeping JavaScript well organized. But before I do, let’s go over a few prerequisites.
Namespace Your Code
One of the worst and most common JavaScript mistakes is assigning variable onto the global namespace (aka ‘window’) if you’re running JavaScript in a browser. This can lead to conflicting functions between you and other developers. And is just, well, messy. The best way to avoid to do this is namespacing as shown in this example:
window.NR = window.NR || {};
window.NR.myFunction = function () {
// your code...
};
And avoid this example:
function myFunction () { // your code... };
Use Strict Mode
Even inside a namespaced function, there can still be a problem. You can accidentally assign variables to the global namespace. To prevent this, prefix all variable declarations with var or this.
Alternatively, you can use strict mode. As the name implies, strict mode parses your JavaScript in a much stricter format. For example, if you attempt to set a variable that is not yet defined, it will through an error instead of assigning to global / window.
If you’re interested in learning more about strict mode, check out this article on John Resig’s blog.
Lint your JavaScript
JSLint evaluates your JavaScript against Douglas Crockford’s coding suggestions. There are plugins for most of the popular editors to evaluate code including Sublime Text 2, Textmate and Vim.
The main benefits of using JSLint are:
* Your code is checked for errors before running, saving you time and debugging effort.
* Sharing linted code in a team unifies coding styles, making code more readable and consistent.
Even if you disagree with some of Douglas’s assertions about how your code should be formatted, you should still use JSLint. You can opt out of the rules with preference setting or comments on the top of your JavaScript file.
I prefer using comments because it gets parsed in the same way when another developer works on you file. This prevents you from getting conflicting parsing results when one of your teammates sets different preferences.
To give you example, here are my standard JSLint configuration setting comments:
/*global NR:true, jQuery:true, Backbone:true, $:true*/ /*jslint browser: true, white: true, vars: true, devel: true, bitwise: true, debug: true, nomen: true, sloppy: false, indent: 2*/
The global declarations tell JSLint which variables to expect on the global namespace – JQuery, Backbone, etc. If it encounters other, it will throw and error. The JSLint options determine what rules are opted into or out of. See the full list of rules on the JSLint website.
OK! Now that’s out of the way, let’s look at a couple of JavaScript patterns I commonly use.
The Module
The module pattern is great if you only need one, such as in a navigation system, and you want to be able to access the object from any scope. By convention, a module should be camelCased with a lower case first letterer.
There are many benefits and drawbacks to using the module pattern:
Pros:
* There’s no need to instantiate, just begin calling methods on it.
* It’s accessible from anywhere. There’s no need to retain a handle to your instance.
* It keeps state and variable values.
Cons:
* You can only have one. Don’t make ten of these for each type of item on the DOM or a similar situation.
* You don’t have a constructor function, so it won’t be fired automatically like with an instance.
* If you need initialization on the module, you need to call it manually the first time it’s used.
Here’s an example module:
(function () {
"use strict";
window.NR = window.NR || {};
window.NR.myModule = {
myVariable: "foo",
initialize: function () {
// your initialization code here
},
anotherMethod: function () {
this.myVariable = "foobar";
}
};
}());
And here’s how it can be used:
NR.myModule.initialize(); NR.myModule.anotherMethod(); console.log(NR.myModule.myVariable); // outputs // "foobar"
Classes
Some people will argue that your should never use ‘new’ when working with JavaScript as there are no true classes in the language. However, I find this pattern extremely helpful for a number of reasons described below. Also, many popular frameworks such as Backbone use class instantiation / extension patterns. Naming conventions for classes is CamelCase with an upper case first letter.
Some of the benefits of this pattern are:
* It’s great for when you have many of an item and each needs its own state.
* It’s a familiar OOP pattern / workflow for many developers.
* It has a constructor function that’s immediately fired on instantiation.
But the drawbacks are:
* You have to remember to instantiate before you can use it. If you don’t, it will cause errors.
* You have to keep a handle to the instance that’s returned from the constructor.
Here’s an example class:
window.NR = window.NR || {};
window.NR.MyClass = (function () {
"use strict";
function MyClass(val) {
this.instanceVar = MyClass.staticVar + val;
}
MyClass.staticVar = "prefix-";
var instanceVar = "";
MyClass.prototype.exampleFunction = function () {
alert('i am an additional function');
};
return MyClass;
}());
And how it can be used:
var instance1 = new NR.MyClass('class 1');
console.log(instance1.instanceVar);
NR.MyClass.staticVar = 'PREFIX-';
var instance2 = new NR.MyClass('class 2');
console.log(instance2.instanceVar);
// Outputs
// "prefix-class 1"
// "PREFIX-class 2"
Summary
I hope these patterns help you keep your JavaScript better organized. What other patterns do you use? Share yours in the comments below.
Sign up here. It's free, so why not?


Good tips. These can be taken to the next level by reading the book “JavaScript Patterns” by Stoyan Stefanov a developer from Yahoo. This book is the most education book I’ve read on the subject and really explains how to use patterns properly and JS Lint among other things. It is a good read from a novice to expert.
There is no hidden agenda and I am not associated to the author in any way. It was that good of a book its worth getting the word out there.
tuzemec Reply:
October 12th, 2012 at 5:40 am
Stoyan is at Facebook now.
And yep, the book is really good.
Posted: 9 October 2012 at 2:42 pm by Greg Beaven
Yes I really enjoyed that book as well. Some patterns from his book have made their way into my workflow as well.
Thanks for the comment!
Posted: 9 October 2012 at 3:00 pm by David Morrow
I’ll second the recommendation for Stefanov’s book. (Though I’ll point out that though it was published while he was at Yahoo!, he’s since moved on to Facebook.) Addy Osmani also just published a book on patterns that’s worth checking out.
Your module example is a good one, but why not use the exporting module pattern? (Example in this Gist.) That way the module itself is decoupled from the namespace and (depending on the contents of the module) could be re-used in other environments.
Great post overall. Thanks for sharing.
David Morrow Reply:
October 10th, 2012 at 9:43 am
Thanks for the Gist.
If I understand it correctly this is the pattern that allows you to protect certain variables and functions from being accessible outside the module.
Very helpful in some circumstances and I can understand the use case for it. But I personally dont find myself needing to protect variables and functions often.
Thanks for sharing!
kyb Reply:
October 12th, 2012 at 6:10 am
I prefer using this style, but it doesn’t play well with the jsdoc-toolkit.
Posted: 9 October 2012 at 6:50 pm by Rob F.
Thanks for the tips!
Posted: 10 October 2012 at 2:33 am by fotografo boda valencia
Also one of the drawbacks with using classes in JavaScript is the fact that you need to care about retaining the context that could be non-trivial, i.e. this in event listener assigned in a class method would not be the same this as in “outer scope”. Sure, there are ways to deal with it, but they do not look very nice.
David Morrow Reply:
October 10th, 2012 at 9:32 am
Agreed,
for scope issues i like using jQuery $.proxy method, or Underscore’s _.bind method. Doesn’t remove the problem, but definitely helps.
Thanks for the comment!
Posted: 10 October 2012 at 4:34 am by Sergey Kovalyov
I’ve always been fond of creating JavaScript classes by doing something like:
var MyClass = function() {
// private
var myVar = 1;
function doSomethingPrivate() {...}
// return public members
return {
doSomethingPublic: function() {...},
doSomethingPublic2: function() {...}
};
}
More or less the same as your example above, but less verbose than using prototype.
Tom Reply:
October 13th, 2012 at 1:41 am
Unless I’m missing something, this won’t allow you to create multiple instances of MyClass using new, which is what David’s second pattern achieves?
Posted: 11 October 2012 at 11:46 pm by Brennan
Also try qbaka.net to monitor JavaScript errors that users experience in production.
Posted: 12 October 2012 at 2:11 am by Andrew
With all due respect to your definition of the module pattern; it seems incomplete as you portray it. Mind you, the term “module” is ambiguous, and therefore somewhat speculative. While your implementation publishes an object with a public API and encapsulated internals, both of which are important aspects of modularity, I don’t feel that in and of itself solves the greater goals of object relationship management, wherein we’d like to loosely-couple object references through inversion of control. Publishing modules to static URIs within a namespace tree forces them to look outside their factory scope to make references to other components, which cements application architecture and defeats encapsulation. The result begins to feel suspiciously like traditional speghetti code within a fancier wrapper. I’d argue that true modularity takes this a step further by completely encapsulating a component’s behavior from all out-of-scope references (window being of of them), in favor of loosely-coupled references made through dependency injection. Modular frameworks such as Require.js take this to the extreme by cometely eliminating the need for application namespace through its dependency manager.
David Morrow Reply:
October 16th, 2012 at 8:52 am
Thanks for your comments.
The above patterns i shared on the post are simply patterns i find myself using often that work well for many situations.
I’d love to see a gist of the pattern you are referencing, and I could possibly comment on it or even learn something myself.
- Dave
Greg Reply:
October 22nd, 2012 at 7:45 am
Sure thing, a simple example without using libraries may look generally like this:
window.MyApp = (window.MyApp || {});
MyApp.MyUtils = (function() {
return {
doHandyThing1: function() {},
doHandyThing2 function() {}
};
}());
MyApp.MyModule = (function( utils ) {
var privateValue = "Encapsulated value. No one else can touch this.";
var ModuleExport = function() {
// Do constructor stuff.
utils.doHandyThing1(); // << Take advantage of imported utilities!
};
ModuleExport.prototype = {
publicValue: "Anyone can change this.",
publicMethod: function() {
// Anyone can call this.
},
getEncapsulatedValue: function() {
// Anyone can call this to GET the encapsulated value.
// However, nothing else can SET the encapsulated value.
return privateValue;
}
};
// Export a single instance of our module:
return new ModuleExport();
}( MyApp.MyUtils ));
The key concept here that differs from your proposed module pattern is inversion of control: MyUtils and MyModule are two separate modules, and therefore, neither should be aware of each other within the application superstructure. While we could technically reference “MyApp.MyUtils.doHandyThing1″ from within MyModule, this violates the rule of modules being self-contained and ignorant of what’s outside of them. To loosely couple this relationship, MyApp.MyUtils is provided once in the MyModule scope invocation (final line of code), at which time it becomes available as a local variable within the MyModule scope. This relationship of dependency injection enforces encapsulation, keeping modules easier to manage and test. Frameworks such as Require.js are designed to automate this loosely coupled dependency management.
David Morrow Reply:
November 6th, 2012 at 3:46 pm
thanks for the update,
I like your pattern very much. I think the phrase “dependency injection” sums up what makes it so appealing.
Thanks for sharing this, this will make it into my snippets.
Posted: 14 October 2012 at 5:58 pm by Greg