Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string zero, zero, empty string, null

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?

like image 551
ihtus Avatar asked Dec 08 '14 21:12

ihtus


2 Answers

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') { }
like image 89
Felix Kling Avatar answered Sep 21 '22 04:09

Felix Kling


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

like image 32
Alex Char Avatar answered Sep 18 '22 04:09

Alex Char