-1

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?

Flimzy
  • 60,850
  • 13
  • 104
  • 147
  • 1
    What defines an "empty" date? Indeed I think any date object should never return true for a condition like that. – Klaycon Mar 04 '20 at 21:52
  • You probably shouldn't be handling all these cases in a single check, rather figure out exactly what you need and check for its validity. For example, if you're checking for a valid date, use `lodash.isDate` rather than checking if it's `undefined`, `null`, `string`, `number`, or whatever. – goto1 Mar 04 '20 at 21:56
  • The only condition I can think of for a date being empty would be `new Date(0)` ( 0 milliseconds from epoch). But that would never be a value you'd have to deal with in the _vast_ majority of cases. – Alex Wayne Mar 04 '20 at 21:59
  • well needed a clean answer to accomodate for dates also –  Mar 04 '20 at 22:09
  • @Klaycon any date which is null blank, undefined, or empty –  Mar 04 '20 at 22:09
  • @Artportraitdesign1 dates cannot be null or blank or undefined or empty. if a variable that's supposed to have a date in it has one of those values instead, it *is not* a date, and your current condition will catch this on the `test == null`. please be more specific and describe what exact value is giving you undesirable results – Klaycon Mar 04 '20 at 22:11
  • If you're strictly testing for a `Date` then you should use something like `date-fns.isValid`, then no matter what you pass (`null`, `undefined`, `blank`, **whatever**), it will give you the right result - https://date-fns.org/v2.10.0/docs/isValid. Simply create a `Date` object with value that you're given and do the check. – goto1 Mar 04 '20 at 22:58

1 Answers1

0

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.

Klaycon
  • 8,967
  • 6
  • 26