Checking for zero in JavaScript except zero

I use the following syntax to ensure that my input parameters are non-zero.

function hazaa(shazoo){
  shazoo = shazoo || " ";
}

It works for everything that I tested for except zero.

null → "
" beep "->" beep "
4 → 4
but ...
0 →" "

I assume that null is considered null or false, therefore creating a gotcha. What is the syntax to get this right so that zero is zero?

If the problem greatly simplifies the syntax suggestion, we can assume that the input will be char, string, number, or zero.

+4
source share
7 answers

-, , . undefined , null; .

//so better use this
shazoo = shazoo == null ? " " : shazoo;

//than this
shazoo = shazoo === null || shazoo === undefined ? " " : shazoo;
+1

, , .

, , " ", null, ,

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

, JavaScript. , . shazoo || " " " ", shazoo .

+7

Boolean(0) false, ""

( fiddle)

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

,

0 .

, , ?

shazoo = shazoo === null ? " " : shazoo;
+1

:

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

=== , -

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

else

shazoo = shazoo //no sense

+1

ES6 , , undefined.

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

null

+1

Source: https://habr.com/ru/post/1623091/


All Articles