I am checking if a value is not falsy with
if (value) { .. }
but I do want to accept zeros as a (non-falsy) value. How is this normally done? Would it be
if (value || value === 0) { .. }
or what?
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
Use the strict inequality operator to check if a value is not equal to 0 , e.g. myVar !== 0 . The strict inequality operator checks if two values are not equal and returns a boolean result - true if they aren't equal, and false otherwise.
These are the following falsy values in TypeScript and JavaScript: 0. false.
if (value || value === 0) { .. }
is cleaner way, no problem.
Just for fun try this
val = 0; if(val){ console.log(val) } //outputs 0 **update - it used to be.. but now it seems it doesnt in chrome
And
var val = 0; if(val){ console.log(val) } //outputs nothing
I would use value || value === 0
. It's fine whichever way you do it but IMO this is the cleanest option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With