Deprecated: Assigning the return value of new by reference is deprecated in /home/content/27/11020327/html/wp-settings.php on line 267

Deprecated: Assigning the return value of new by reference is deprecated in /home/content/27/11020327/html/wp-settings.php on line 269

Deprecated: Assigning the return value of new by reference is deprecated in /home/content/27/11020327/html/wp-settings.php on line 270

Deprecated: Assigning the return value of new by reference is deprecated in /home/content/27/11020327/html/wp-settings.php on line 287
PHP style empty function for JavaScript | ProDevTips - Web Development Tutorials


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: ,