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!
James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.