Konrad Viltersten
Konrad Viltersten

Reputation: 39118

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.

Upvotes: 4

Views: 104

Answers (7)

gurvinder372
gurvinder372

Reputation: 68393

Boolean(0) outputs false, so it took second option ""

you can try (check this fiddle)

function hazaa(shazoo){
  return shazoo == null ? " " : shazoo;
} 
hazaa(0); //output 0

Upvotes: 1

Blindman67
Blindman67

Reputation: 54026

New notation

You can also in ES6 use the default argument notation that will default if undefined is passed for that argument.

function foo(shazoo = "default"){
    console.log(shazoo);
}

foo();          // "default"
foo(undefined); // "default"
var bar;        // 
foo(bar);       // "default"
foo("my string"); // "my string"
foo(null);      // null

It does not handle null

Upvotes: 1

Thomas
Thomas

Reputation: 3593

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;

Upvotes: 1

Andres
Andres

Reputation: 10717

Use the following:

if (shazoo === null){
...
}else{
...
}

Upvotes: 1

Anand Singh
Anand Singh

Reputation: 2363

You can us === operator and the best way would be

if (shazoo === null)
 shazoo = " ";

No need to use else

shazoo = shazoo //no sense

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239473

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.

Upvotes: 7

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

I'm guessing that the zero is regarded as null or false

Yes 0 is treated as false.

What's the syntax to get it right, so that zero is zero?

You can try to use

shazoo = shazoo === null ? " " : shazoo;

Upvotes: 1

Related Questions