Detect empty values in JavaScript

15. February 2010 11:14

Okay, this is a quick one. There are several states that can be considered empty in JavaScript, a non-numeric value in a number, an invalid date, and empty string, an undefined value, and a null value. The issue is that some of these require testing against isNaN, and others will evaluate as matching null or an empty string (ex: the number zero and the boolean false). What I wanted was a simple method to check for a non-empty object or string, here it is.

function isEmpty(obj) {
    if (typeof obj == 'undefined' || obj === null || obj === '') return true;
    if (typeof obj == 'number' && isNaN(obj)) return true;
    if (obj instanceof Date && isNaN(Number(obj))) return true;
    return false;

How it works, is first it tests for an 'undefined' object, an object that is explicitly equal to null, or explicitly equal to an empty string. If it matches, it's empty. From here there's some more specific checking, if it's a number type of variable, and isNaN (Not a Number), then it's empty. If it's a date, and Number(obj) (which gets the value of the date as a Number) isNaN, then it's an invalid date, and ergo isEmpty. Otherwise the isEmpty returns false (valid, non-empty value). Hope this helps some of you. :)

Comments are closed


Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.