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!
Related posts:
- Techy Treasures #4: What’s inside a dollar function? The $ function is a common feature of all of...
- Techy Treasures #3: When is a mouseout not a mouseout? I've had this little gadget in my toolbox for a...
- Truthy and Falsy: When All is Not Equal in JavaScript Anything in JavaScript can be considered to be either truthy...
- Cross-browser JSON Serialization in JavaScript JSON serialization can be incredibly useful, but few browsers support...
- Techy Treasures #5: Fudging CSS Counters in Internet Explorer CSS Counters are a useful but under-used feature of CSS2...







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
October 16th, 2008 at 8:00 pm
Oooh, this is useful. Looking forward to this series!
October 16th, 2008 at 10:13 pm
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.
October 20th, 2008 at 9:47 pm
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.
October 21st, 2008 at 9:30 am
Sorry, should have toned that down a bit.
October 21st, 2008 at 8:17 pm
I lol’d at that comment by RIM
October 22nd, 2008 at 10:36 pm
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).
October 23rd, 2008 at 7:51 am
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.
October 23rd, 2008 at 8:33 am
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.
October 23rd, 2008 at 9:35 am
“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.
October 28th, 2008 at 10:26 am
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.
October 28th, 2008 at 3:14 pm
Great, thanks.
December 16th, 2008 at 2:18 am