How to check if variable is not falsy but 0 passes in Javascript

1.2k Views Asked by At

Is there an elegant way to check if variable is NOT falsy but in case of 0 it passes. The issue with this way of verifying if(var !== undefined && var !== null) is that it's long and doesn't cover all cases like undecalred or NaN. I'm also using typescript and declare it as optional number.

2

There are 2 best solutions below

4
Pointy On BEST ANSWER

You can do exactly what your first sentence asks:

if (!x && x !== 0)

means literally "if x is falsy and x is not 0".

Also the == and != comparison operators explicitly consider null and undefined to be equal, so

if (x != null)

is true for both null and undefined. (That's !=, not !==.)

0
SRK45 On

function Check(input) {
   if (!input && input!==0){
    return "falsy";   
   }
   else if (input === 0){
    return "zero";
   
   }
   
}
console.log(Check(0));
console.log(Check(false))