Techy Treasures #1: Feelin’ Empty

Tweet

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:

  • 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!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Wardy

    Great idea, looking forward to these.

    It could be useful to create an account on snipplr or somewhere similar that would contain these functions for ease of finding

  • http://www.magain.com/ mattymcg

    Oooh, this is useful. Looking forward to this series!

  • RIM

    I wish Crockford would see this.
    This is taking the falsy nature of JavaScript and making it 10 times worse.

    And what happend to semantics?
    Can a boolean be empty now? Or a number, can it be empty?
    Is a string empty when it is “0”?

    If you have no regard for types anyway,
    why write if(empty(id)) when you can simply write if(!id)?

    Seriously, is this a solid, proven idea that you can use in the wild with confidence?
    You’d be out the door in seconds if you wrote this code at our company.

  • http://www.brothercake.com/ brothercake

    Yeah that’s somewhat fair comment, despite how it was delivered.

    I was thinking more in terms of replicating PHP’s function, but since you mention it, yeah it is kinda unsemantic to consider “0”, 0 or false to be empty, it would probably be better only to count empty strings, arrays and objects.

  • RIM

    Sorry, should have toned that down a bit.

  • Bob Carologees

    I lol’d at that comment by RIM

  • Anonymous

    I really have to agree with RIM here, the name of this function is just plain wrong. This is a symptom of many of the things that are wrong with Javascript development these days: people writing functions to be interesting, not to answer a particular problem, just like prototype (another VERY inappropriate name) and jQuery etc.

    I suspect that this is too complex as it stands to be really useful: how many times is the logic for an empty array going to match with this logic for other ‘empty/falsy’ elements?
    I suspect that most people would find the array checking section would work better if it was built recursively (if checking for emptyness).

  • http://www.brothercake.com/ brothercake

    Okay, so a method that only checks things which can be semantically considered to be empty (arrays, objects and strings), and also has the capability to check recursively – that would be more useful and more correct?

    FYI the purpose of writing this in the first place was not to be interesting, it was to solve a specific problem – ie. I get tired of checking variables, constantly typing things like this:

    if(typeof somevar != 'undefined' && somevar != null) { ...

    So I wanted something that could make that kind of checking easier. But I concede that, along the way, I’ve gone too far and undermined the type-sanctity of some kinds of data.

  • pd

    I think this is a great idea for a JS library if implemented well. I’ve posted it to the jQuery list for comment:

    http://groups.google.com/group/jquery-en/t/b0ae83b6b20a1661

    I’ll probably get flamed but that’s the flamer’s issue not mine.

  • Breton

    “if(typeof somevar != ‘undefined’ && somevar != null) { …”

    then stop writing that and write this instead:

    if(somevar) { …

    which works exactly the same
    in javascript

    !”” === true;
    !0 === true;
    !false === true;
    !undefined === true;
    !([]).length === true;

    and as for objects, it is impossible for an object in javascript to ever be truly empty (unfortunately), because it always has the properties from Object.prototype, and those cannot be deleted.

    It is possible to have an object with no enumerable properties.
    function hasEnumerableProperties (o) {
    var a= false,i;
    for ( i in o ) {
    a = a && !!i;
    }
    return a;
    }

    gets you there if you really need it.

  • http://www.brothercake.com/ brothercake

    Nah man, if you do that then how do you differentiate between an object that isn’t defined, and an object that is defined but has the value false, or a value that equates to false? You always have to use typeof, you cannot rely on automatic type conversion (except for DOM objects, because the ECMA spec requires that null evaluates to false). If all of that were not an issue, then there’d have nothing wrong with my method in the first place.

    And yes, an object is never truly empty, but as I said, what this does it return whether the object has any enumerable properties, which is what’s usually needed, and is why it includes the hasOwnProperty check.

  • Cor-Paul

    Great, thanks.