Common Idioms in JavaScript development

These are some of the common idioms I find myself using again and again. I am going to keep this as a live document and will update as I discover more useful idioms.

Disclaimer: I’ll be using the Underscore library in all of my examples

Use Array.join to concatenate strings

It is quite common to build html in strings, especially when you are writing a custom formatter or just plain building simple views in code. Lets say you want to output the html for 3 buttons:

1 	var html = '<div class="button-set">' + 
2 		'<span class="button">OK</span>' +
3 		'<span class="button">Apply</span>' +
4 		'<span class="button">Cancel</span>' +
5 	'</div>';

This works, but consider the alternate version, where you build the strings as elements of an array and join them using Array.join().

1 var html = [
2 	'<div class="button-set">'
3 		'<span class="button">OK</span>',
4 		'<span class="button">Apply</span>',
5 		'<span class="button">Cancel</span>',
6 	'</div>'
7 ].join('');

It reads a little better and can almost look like real-html with the identation ;)

Minimize use of if/else blocks by creating object hashes

Lets say you want perform a bunch of different actions based on the value of a certain parameter. For example, if you want to show different views based on the weather condition received via an AJAX request, you could do something like below:

 1 function showView(type) {
 2 	if (_.isObject(type)) {
 3 		// read object structure and prepare view
 4 	}
 5 	else if (_.isString(type)) {
 6 		// validate string and show the view
 7 	}
 8 }
 9 
10 function showWeatherView(condition){
11 	
12 	if (condition === 'sunny') showView('sunny-01');
13 	else if (condition === 'partly sunny') showView('sunny-02');
14 	else if (condition === 'cloudy') showView('cloudy-01');
15 	else if (condition === 'rain') showView({ type: 'rain-01', style:'dark' })
16 }
17 
18 $.get('http://myapp.com/weather/today', function(response){
19 	
20 	var condition = response.condition;
21 
22 	// Show view based on this condition
23 	showWeatherView(condition);
24 });

You will notice in showWeatherView(), there is lot of imperative noise with if/else statements. This can be removed with an object hash:

 1 function showWeatherView(condition){
 2 
 3 	var viewMap = {
 4 		'sunny': 'sunny-01', 
 5 		'partly sunny': 'sunny-02',
 6 		'cloudy': 'cloudy-01',
 7 		'rain': { type: 'rain-01', style:'dark' }
 8 	};	
 9 
10 	showView(viewMap[condition]);
11 }

If you want to support more views, it should be easier to add it to the viewMap hash. The general idea is to look at a piece of code and think in terms of data + code. What part is pure data and what part is pure code. If you can make the separation, you can easily capture the data part as an object-hash and write simple code to loop/process the data. As a side note, if you want to eliminate the use of if/else, switch statements, you can have Haskell-style pattern-matching with the matches library.

Make the parameter value be of any-type

When you are building a simple utility library/module, it is good to expose an option that can be any of string, number, array or function type. This makes the option more versatile and allows for some logic to be executed each time the option value is needed. I first saw this pattern used in libraries like HighCharts and SlickGrid and found it very natural.

Let’s say you want to build a simple formatter. It can accept a string to be formatted using one of the pre-defined formats or use a custom formatter. It can also apply a chain of formatters, when passed as an array. You can have the API for the formatter as below:

 1 function format(formatter, value) {
 2 	var knownFormatters = {
 3 		'###,#': function(value) {},
 4 		'mm/dd/yyyy': function(value) {},
 5 		'HH:MM:ss': function(value) {}
 6 	},
 7 		formattedValue = value;
 8 
 9 	if (_.isString(formatter)) {
10 
11 		// Lookup the formatter from list of known formatters
12 		formattedValue = knownFormatters[formatter](value);
13 
14 	}
15 	else if (_.isFunction(formatter)) {
16 
17 		formattedValue = formatter(value);
18 
19 	}
20 	else if (_.isArray(formatter)) {
21 
22 		// This could be a chain of formatters
23 		formattedValue = value;
24 		_.each(formatter, function(f) {
25 			formattedValue = format(f, formattedValue); // Note the recursive use format()
26 		});
27 
28 	}
29 
30 	return formattedValue;
31 }

As an addendum to a multi-type parameter, it is also common to normalize the parameter value to an object hash and remove type differences.

Use IIFE to compute on the fly

Sometimes you just need a little bit of code to set the value of an option. You can either do it by computing the value separately or do it inline by writing an Immediately Invoked Function Expression (IIFE):

1 var options = {
2 	title: (function(){
3 		var html = '<h1>' + titleText + '</h1>';
4 		var icons = '<div class="icon-set"><span class="icon-gear"></span></div>';
5 
6 		return html + icons;
7 	})(),
8 	buttons: ['Apply', 'Cancel', 'OK']
9 };

In the above code there is little bit of computation for the title text. For simple code like above it is sometimes best to have the logic right in there for improved readability.