2

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.

valentin Ivanov
  • 83
  • 1
  • 10
  • If you just have `number?` in TS, then you don't need to check *all* falsy values, you just need to check for `undefined` and maybe `NaN`. – VLAZ Jul 13 '21 at 14:56

2 Answers2

3

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 !==.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • will `(x != null)` consider cases like `undeclared` or `NaN`? – valentin Ivanov Jul 13 '21 at 14:59
  • 1
    @valentinIvanov undeclared variables will always throw an error if you try to read them. With that said you *should **not*** have undeclared variables. There is a serious problem with the code if a variable might exist or not at some point. You should have reliable code. – VLAZ Jul 13 '21 at 15:01
  • @valentinIvanov as for `NaN` - no `NaN != null` is `true`. Only `undefined` and `null` are loosely equal to each other https://dorey.github.io/JavaScript-Equality-Table/ – VLAZ Jul 13 '21 at 15:02
  • @valentinIvanov The `==` and `!=` rules consider `null` and `undefined` to be the same, but only those two falsy values. – Pointy Jul 13 '21 at 15:02
0

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