xdevel2000
xdevel2000

Reputation: 21364

expression evaluation with boolean values

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???

Upvotes: 2

Views: 383

Answers (3)

ntownsend
ntownsend

Reputation: 7630

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.

Upvotes: 0

Macmade
Macmade

Reputation: 53950

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

Upvotes: 2

Pointy
Pointy

Reputation: 413712

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.

Upvotes: 4

Related Questions