Monday 10 December 2012

empty()

This is just brilliant and deserves to be kept forever:

function empty(data) {
    if (typeof (data) == 'number' || typeof (data) == 'boolean') {
        return false;
    }
    if (typeof (data) == 'undefined' || data === null) {
        return true;
    }
    if (typeof (data.length) != 'undefined') {
        return data.length == 0;
    }
    var count = 0;
    for (var i in data) {
        if (data.hasOwnProperty(i)) {
            count++;
        }
    }
    return count == 0;
}

It's from the fabulous JSPro.

Yon peeps who are Java and C# heads at work used to sneer at my various attempts to check to see if a value was null or an empty string, well not any more thanks to this little gem!

No comments:

Post a Comment