In this post I’ll share three might-come-in-handy javascript techniques I often use. These techniques are: using the javascript ‘with’ keyword, using the ‘String.indexOf’ function to shorten if conditions, and using the ‘arguments’ array to get a better understanding of how (undocumented) functions work.

The javascript ‘with’ keyword

The javascript with keyword is a handy function when you’re dealing with long namespaces like objname.attributename.element.style.display. Here’s an example:

// Original code.
object.attr.element.style.display = 'block';
object.attr.element.style.padding = '10px';
object.attr.element.style.fontSize = '1.4em';

// Code using 'with'.
with(object.attr.element.style){
	display = 'block';
	padding = '10px';
	fontSize = '1.4em'
}

// Another example.
var foo = object.attr.arrayObj[0].value;
var bar = object.attr.arrayObj[1].value;
var baz = object.attr.arrayObj[2].options[object.attr.arrayObj[2].selectedIndex];

// Example nested 'with'
with(object.attr){
	var foo = arrayObj[0].value;
	var bar = arrayObj[1].value;
	with(arrayObj[2]){
		var baz = options[selectedIndex];
	}
}

Note that code without with is slightly faster because with forces the specified object to be searched first for all unqualified name lookups. The with keyword can help reducing the file size of your javascript. Read more about it on Mozilla Development Center.

Replacing if conditions with ‘String.indexOf’

If you have an if condition and you’re comparing a variable with some string, use String.indexOf to shorten the condition:

var tagname = document.getElementById('someElement').tagName.toLowerCase();

if(tagname == 'div' || tagname == 'input' ||
	tagname == 'p' || tagname == 'span'	||
	tagname == 'blockquote'){
	// do some action
}

if('div|input|p|span|blockquote'.indexOf(el.tagName.toLowerCase()) != -1){
	// do some action
}

This technique also reduces the file size, but the computation if the index might take a little longer. When you’re not using this in loops that loop more than 100 times, I don’t think you’ll notice a delay.

Using the ‘arguments’ variable

I find myself using the arguments array quite a lot when debugging. It’s an easy way to understand how a function’s called, and which arguments are passed to it. In some older browsers there are two handy properties in the arguments variable: arguments.caller and arguments.callee. Modern browsers deprecated those two, but kept the arguments.length property. Here’s an example:

// You want to know which arguments are passed to someFunc().
function someFunc(){
	for(var i = 0; i < arguments.length; i++){
		alert(arguments[i]);
	}
}

I think most people already knew this one. But when you're learning a new javascript lib with a lack of documentation, or trying out code someone else wrote (without proper documentation), this technique let's you understand functions much quicker/better. Read more about arguments on the Mozilla Development Center.