How to check if a value is not null and not empty string in JS

If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:

if(data !== null && data !== '') {
   // do something
}

Notice that I changed your code to check for type equality (!==|===).

If, however you just want to make sure, that a code will run only for “reasonable” values, then you can, as others have stated already, write:

if (data) {
  // do something
}

Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).

The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.

Leave a Comment