JavaScript Best Practices

Contact Us or call 1-877-932-8228
JavaScript Best Practices

JavaScript Best Practices

Namespacing Variables

Avoid polluting the global namespace (the elements owned by window). Instead use self-executing anonymous functions or variables and functions owned by a single, global object.

Global Namespace Variables

Rather than declaring a number of separate global items, which can result in name collisions, use the same practice that jQuery uses -- create one global object that owns everything else.

var MyGlobal = {
	someVariable: 5;
	someFunction = function(a) { ... }

MyGlobals.someVariable = 10;

Self-Executing Anonymous Functions

We have seen these many times already. They contain variables that are global to any functions defined inside the self-executing functions scope, and, as such, are good for jQuery code to run when the document is ready. They are also good for adding plugins to jQuery or another external global variable.

Cache Frequently Used Values

Cache Length During Loops

In a for loop, don't access the length property of an array every time; cache it beforehand.

var myLength = myArray.length;

for (var i = 0; i < myLength; i++) {
	// do stuff

Cache Retrieved Elements, Chains of Element Lookups, and jQuery Collections

Although document.getElementById is optimized, it is still inefficient to do it multiple times for the same element. Retrieve it once and store it in a variable. Even if the DOM changes around it, the reference is still valid.

Following chains of object property references can be expensive, particularly if done in loops.

As mentioned before, a query can be expensive, so caching the results will help speed up code if the collection won't change.

Append New Content Outside of a Loop

Touching the DOM comes at a cost; if you're adding a lot of elements to the DOM, do it all at once, not one at a time.

// This is bad
$.each(myArray, function(i, item) {
	var newListItem = '<li>' + item + '</li>';

// Better: do this
// A document fragment is a node that is a container -
// when you append it somewhere, the fragment node
// disappears, but its contents are appended
var frag = document.createDocumentFragment();

$.each(myArray, function(i, item) {
	var newListItem = '<li>' + item + '</li>';

// Or do this
var myHtml = '';

$.each(myArray, function(i, item) {
	myHtml += '<li>' + item + '</li>';

Beware Anonymous Functions

Despite our use of them throughout the course, too many anonymous functions bound everywhere are a pain. They're difficult to debug, maintain, test, or reuse. Instead, use an object literal to organize and name handlers and callbacks that are at all complex or lengthy.

// Bad
$(document).ready(function() {
	$('#go').click(function(e) {
		$('#details').slideDown(function() {

	$('#results').load('somepage.html #' + tag, function() {

// Better
var Globals = {
	url: 'somepage.html',

	onReady : function() {
		$('#results').load(Globals.url + ' #' + tag, Globals.afterLoad);

	showDetails : function(e) {

	afterSlide : function() { ... },

	afterLoad : function() { ... }


Also note the moving of the embedded url to a variable - it is tough to find things like that when they need to be edited if they are inline in code.