JavaScript
Article
By James Edwards

Techy Treasures #1: Feelin’ Empty

By James Edwards
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Techy Treasures is a new, regular feature where we’ll be publishing tips, tricks and code snippets for web developers. These are not blue-sky bubbles, they’re solid, proven ideas that you can use in the wild with confidence.

And to start with, a neat little function that checks whether a variable is empty, inspired by PHP’s function of the same name:

function empty(data)
{
	if(typeof data == 'undefined' || data === null) { return true; }
	else if(typeof data == 'string' && (data === '0' || data.replace(/^s+|s+$/g, '') === '')) { return true; }
	else if(typeof data == 'number' && data === 0) { return true; }
	else if(typeof data == 'boolean' && data === false) { return true; }
	else if(typeof data == 'object')
	{
		if(data instanceof Array && data.length == 0) { return true; }
		else
		{
			var n = 0;
			for(var i in data)
			{
				if(!data.hasOwnProperty(i)) { continue; }
				n++;
			}
			if(n == 0) { return true; }
		}
	}
	return false;
}

So a variable is considered empty if it’s:

--ADVERTISEMENT--

  • undefined
  • null
  • a string, and its value is "0", or an empty string, or only whitespace
  • a number, and its value is 0
  • a boolean, and its value is false
  • an array, and it has no values
  • an object, and it has no enumerable properties

It works for any kind of variable, for example, used as a condition:

if(!empty(data)) 
{
	//data is not empty
}

You could even pass the return value of another process, thanks (as ever!) to JavaScript’s ability to handle almost anything as an argument:

if(!empty(function()
{
	//do some process and return a value
}))
{
	//return value was non-empty
}

I’ve been finding it particularly useful for validating function arguments, for example a simple shortcut function for getting element references:

function get(id)
{
	return document.getElementById(id);
}

But what if the id parameter is empty, or null, or not there at all? We can check all those possibilities with a single statement, and then handle the situation accordingly:

function get(id)
{
	if(empty(id)) { return null; }
	return document.getElementById(id);
}

And there you go — a neat, simple, and elegant method for validating any kind of variable.

See you soon for another Techy Treasure!

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?