Search code examples
javascripttypescriptlodashjavascript-objects

Test if variable is Null, Undefined, Blank, or Empty Object including Date items


How do I check if a Variable (whether, number, string, date, Object, etc)

is null, blank, undefined or empty?

The following fails for any Date, with lodash isEmpty always returning NotEmpty for dates.

if (test == null || test == '' || _.isEmpty(test){
    console.log('variable is empty');
}

Anyway to do this is in a clean manner? Reading the links below,

How to determine if variable is 'undefined' or 'null'?

How do I test for an empty JavaScript object?


Solution

  • Simply testing for the variable's falsiness should cover all of these cases.

    if (!test){
        console.log('variable is empty');
    }
    

    Note that, like your current condition, this condition will never be true for any Date object as there is no defined "falsy" state for Dates. If however a variable that should have a Date has null or undefined instead it will work.