'is false in Javascript? What would be the safest way to distinguish between '' and boolean false?

We are using an external API that returns '' or boolean false, while Javascript seems to find both equal. eg:

var x = '';
if (!x) {
  alert(x); // the alert box is shown - empty

}
if (x=='') {
  alert(x); // the alert box is shown here too  - empty

}
var z = false;
if (!z) {
  alert(z); // the alert box is shown - displays 'false'

}
if (z=='') {
  alert(z); // the alert box is shown here too - displays 'false'

}

      

How can we distinguish between the two?

+2


source to share


4 answers


Use a triple equal

if (x===false) //false as expected
if (z==='') //false as expected

      



A double equal will do type casting, but a triple equal will not. So:

0 == "0" //true
0 === "0" //false, since the first is an int, and the second is a string

      

+27


source


var typeX = typeof(x);
var typeZ = typeof(z);

if (typeX == 'string' && x == '')
else if (typeX == 'boolean' && !typeX)

      



I like Piriks' answer, but here is an alternative.

+2


source


as peirix pointed out: triplex equal signs check both value and type

1 == '1' // true
1 === '1' // false

      

0


source


To avoid these issues, use the jslint validator. This helps to find unsafe transactions.

0


source







All Articles