Reputation: 2811
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?
Upvotes: 11
Views: 17517
Reputation: 4862
Number(variable) seems to produce expected output
Number(0) = 0
Number("0") = 0
Number("") = 0
Number(null) = 0
Number(false) = 0
Upvotes: 6
Reputation: 206525
If you feel funky (just in your exact case-sample) you can do this:
(otherwise undefined
and NaN
will result as false
)
+v===0
Example:
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
});
Upvotes: 3
Reputation: 817010
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') { }
Upvotes: 8
Reputation: 33228
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
Upvotes: 4
Reputation: 65
First of "0" isn't false, its true. Because '0' is a string. Strings if they exist return true. So !"" should return false. That said if your data is returning zeros as strings you can use:
parseInt("0", 10);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
This will return the integer value or NaN. !NaN will return true, and if it is an number of say... 0 it will return !0 so you could do this:
function nullOrEmpty(value) {
return (!value && !parseInt(value));
}
Upvotes: 1
Reputation: 8223
You could very well use a double negative.
var test = 0;
console.log(!!test);
var test = "";
console.log(!!test);
var test = "0";
console.log(!!test);
var test = null;
console.log(!!test);
Although "0"
is not an empty string so it evaluates to true, the rest return false.
Also, I agree with the comment that dfsq made in that you shouldn't rely on this. You should know and understand what types your variables are holding.
Upvotes: 0