@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?
2
Answers
The obvious solution is the verbose (when you need to check multiple values it quickly becomes crowded in your condition).
I also thought of this, a bit shorter but less obvious to read
Keeping the code from becoming crowded is a good goal. You can define your own functions, like so:
Your original code block changes as follows, and is just as easy to read:
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/