PHP style empty function for JavaScript

I often find myself wanting the empty() function of PHP in JavaScript, here it is:

function empty(val){
	if(val == null || val == undefined)
		return true;
		
	switch(typeof val){
		case 'string':
			if(val.length != 0)
				return false;
			break;
		case 'number':
			if(val != 0)
				return false;
			break;
		case 'boolean':
			if(val == true)
				return false;
			break;
		case 'object':
			var hasProps = false;
			for(var i in val) { hasProps = true; }
			if(hasProps){
				if(val['length'] != 0)
					return false;
			}
			break;
		default:
			return false;
			break;
	}
	return true;
}

Note how heavily we rely on typeof to inspect the data.

Related Posts

Tags: ,