0
@Input() a: number;

// Check of null or undefined
if (a)
  // do stuff

With the usual check, the value 0 will also be considered as false and the variable will not pass the if.

There is already a lot of questions around this but I could not find anything that handles the value zero.
Is there anything like the a?.b of typescript but for simple type?

ymoreau
  • 3,402
  • 1
  • 22
  • 60

2 Answers2

0

The obvious solution is the verbose (when you need to check multiple values it quickly becomes crowded in your condition).

if (a !== undefined && a !== null)
  // do stuff

I also thought of this, a bit shorter but less obvious to read

if (a || a === 0)
  // do stuff
ymoreau
  • 3,402
  • 1
  • 22
  • 60
0

Keeping the code from becoming crowded is a good goal. You can define your own functions, like so:

function isBlank(s) {
    return (undefined === s || null === s || "" == s.trim());
}
function isZero(s) {
    return (!isBlank(s) && "0" == s.trim());
}

Your original code block changes as follows, and is just as easy to read:

// Check of null or undefined
if (isZero(a))
  // do stuff

For more information on the falsy values in JavaScript, here are a few good resources:

https://stackabuse.com/javascript-loose-equality-operator-vs-strict-equality-operator/

All falsey values in JavaScript


To play around with some additional values:

https://jsfiddle.net/Lr98kzsa/

JonathanDavidArndt
  • 2,518
  • 13
  • 37
  • 49