tags:

views:

159

answers:

4

We use an external API whcih returns '' or boolean false while Javascript seems to find the both equal. for example:

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?

+21  A: 

Use the triple equal

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

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

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

as mentioned by peirix: tripple equal signs check both the value and the type

1 == '1' // true
1 === '1' // false
Nicky De Maeyer
As you mentioned, it's been mentioned before. Why mention it again?
Alex Barrett
because at the time I posted this he failed to mention that it checks for value AND type...
Nicky De Maeyer
+1  A: 
var typeX = typeof(x);
var typeZ = typeof(z);

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

I like Peirix's answer too, but here is an alternative.

Zoidberg
A: 

For avoid this questions use jslint validator. It helps for find unsafe operations.

Anatoliy