Check if there is no null string, null, empty string, null

in PHP:

$var=0;
$var="";
$var="0";
$var=NULL;

to check if $ var is 0 or "0" or "" or NULL

if (!$var) {...}

in jQuery / JavaScript:

$var=0;
$var="";
$var="0";
$var=NULL;

if (!$var) works for every value except "0"

Is there a general way in JavaScript / jQuery for checking all kinds of empty / null / null values, just like php?

+4
source share
6 answers

Is there a general way in JavaScript / jQuery for checking all kinds of empty / null / null values, just like php?

No. In PHP, values ​​converted to booleans give different results than in JavaScript. Thus, you cannot do this exactly like PHP does.

Why not be (a little more) explicit about it, which makes it easier to understand the code?

// falsy value (null, undefined, 0, "", false, NaN) OR "0"
if (!val || val === '0') { }
+5
source

ToBoolean Boolean 11:

Undefined false
     Null false
     ( ).
     false, +0, -0 NaN; .
     , ( );      .
     true

0 false.

http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

+4

( ), :
( undefined NaN false)

+v===0

:

var a = [0, "",  "0", null];
var b = [1, "a", "1", {}];

a.forEach(function(v){
  console.log( +v===0 ); // true, true, true, true
});

b.forEach(function(v){
  console.log( +v===0 ); // false, false, false, false
});
+1

.

var test = 0;
console.log(!!test);

var test = "";
console.log(!!test);

var test = "0";
console.log(!!test);

var test = null;
console.log(!!test);

"0" , true, false.

, , dfsq , . , .

0

"0" , . '0' - . , , true. ! "" false. , , :

parseInt("0", 10);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

This will return an integer value or NaN. ! NaN will return true, and if that number says ... 0, it will return! 0 so you can do this:

function nullOrEmpty(value) {
    return (!value && !parseInt(value));
}
0
source

The number (variable) seems to produce the expected result

Number(0) = 0
Number("0") = 0
Number("") = 0
Number(null) = 0
Number(false) = 0
0
source

All Articles