I'm using the following syntax to ensure that my input parameters aren't null.
function hazaa(shazoo){
shazoo = shazoo || " ";
}
It works for everything I tested for except the zero.
null -> " "
"beep" -> "beep"
4 -> 4
but...
0 -> " "
I'm guessing that the zero is regarded as null or false, hence creating the gotcha. What's the syntax to get it right, so that zero is zero?
If it makes the issue considerably simpler to suggest a syntax, we can assume that the input is going to be a char, string, number or null.
I'm using the following syntax to ensure that my input parameters aren't null.
If all you are trying to do is to use " "
only if the input is null
, then use ternary operator, like this
shazoo = shazoo === null ? " " : shazoo;
This answer lists the values which are considered as Falsy in JavaScript. The table shows that zeroes are considered as Falsy. That is why shazoo || " "
is evaluated to be " "
, when shazoo
is zero.
In my opinion, this is one of the few places where you don't want to do a typesafe comparison. In such places you want to threat undefined the same way as null; and you don't want to write it every time.
//so better use this
shazoo = shazoo == null ? " " : shazoo;
//than this
shazoo = shazoo === null || shazoo === undefined ? " " : shazoo;
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