in PHP:
$var=0;
$var="";
$var="0";
$var=NULL;
to verify 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 for "0"
Is there a general way in JavaScript/jQuery to check all kinds of those empty/null/zero values, exactly like php does?
Is there a general way in JavaScript/jQuery to check all kinds of those empty/null/zero values, exactly like php does?
No. In PHP, the values converted to booleans produces different results than in JavaScript. So you can't do it exactly like PHP does.
Why not be (a bit more) explicitly about it which makes your code easier to understand?
// falsy value (null, undefined, 0, "", false, NaN) OR "0"
if (!val || val === '0') { }
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Object true
0 will return false.
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
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