tags:

views:

38

answers:

3

In Java or other similar languages I can't do:

a < b > c

where a,b,c are boolean types.

In Javascript I can do that and also with other data types values:

var t = 3;
var z = true;

t > z // will be true

Now why the results is true???

+4  A: 

Because Javascript is willing to do type conversions at the drop of a hat. Boolean true is coerced to numeric 1.

Note that 1 == true is true, but 1 === true is false.

Pointy
+1. Also, `a < b > c` will be evaluated as `(a < b) > c` and since `a < b` evaluates to a boolean, `> c` is testing if the resulting casted integer (1 or 0) is greater than c.
Andy E
Indeed. To me, all these explanations constitute reasons to expunge code like that whenever it's encountered :-)
Pointy
A: 

JavaScript first casts the boolean true to a number for the comparison. In this case true is cast to 1.

Many objects will not be cast to numbers though. For example, {} is NaN.

ntownsend
+2  A: 

True will be converted to 1. And 3 is greater than one...

Macmade