Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null in JavaScript works except for zero

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.

like image 462
Konrad Viltersten Avatar asked Dec 11 '22 19:12

Konrad Viltersten


2 Answers

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.

like image 128
thefourtheye Avatar answered Feb 13 '23 07:02

thefourtheye


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;
like image 27
Thomas Avatar answered Feb 13 '23 06:02

Thomas