0

I am looking for check, if my variable is one of : null || undefined || empty string || false

Right now its look messy and long:

const userHasPhoneNumber = user.phone === undefined || 
                           user.phone === "" || 
                           user.phone === false ||
                           user.phone === null ? false : true;           

Is there shortcut?

stark
  • 358
  • 2
  • 10

3 Answers3

1

If you coerce that string to a boolean then it should check all your conditions, which is pretty much checking if user.phone is truthy.

It depends how you want to use it. If you wanted to use it in a condition, i.e. if(userHasPhoneNumber) ... then you can use the string directly : if(user.phone) as it will coerce to a boolean.

If you really need to have a boolean variable then need to cast it to a boolean explicitely:

Either through const userHasPhoneNumber = Boolean(user.phone); or const userHasPhoneNumber = !!user.phone;

Note, as @Bergi commented, that there are more values that are coerced to a false value (falsy values), for example NaN or the number 0 (the string "0" will coerce to true), so it depends what your input is. If it's never a number but either a string/boolean/null/undefined, it should be fine. Here is the list of all falsy values for reference : https://developer.mozilla.org/en-US/docs/Glossary/Falsy

Ricola
  • 1,927
  • 6
  • 15
1

You can shortcut x === undefined || x === null to x == null. For the others, there is no shortcut as there are some falsy number values as well. You could however do

const userHasPhoneNumber = typeof user.phone == "number" || !!user.phone
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
1

Use JavaScript's !!, witch will become false for null, "", undefined and false:

const user = {
  phone_1: null,
  phone_2: "",
  phone_3: undefined,
  phone_4: false
};

console.log(!!user.phone_1);  // false
console.log(!!user.phone_2);  // false
console.log(!!user.phone_3);  // false
console.log(!!user.phone_4);  // false

Note Use this with caution as some results may be different then expected, this answer shows a complete list.

0stone0
  • 11,780
  • 2
  • 20
  • 35