I was reading a good book on JavaScript.
It started with:
Boolean type take only two literal values: true and false. These are distinct from numeric values, so true is not equal to 1, and false is not equal to 0.
However, I observed following:
if(1==true)
document.write("oh!!! that's true"); //**this is displayed**
I know, that every type in JavaScript has a Boolean equivalent.
But then, what’s the truth?
It’s true that
trueandfalsedon’t represent any numerical values in Javascript.In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).
In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It’s possible to convert between boolean values and numerical values, but it doesn’t happen automatically.
Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.
For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using
if (1) {...}works just as well asif (true) {...}.When comparing values, like in your example, there is a difference between the
==operator and the===operator. The==equality operator happily converts between types to find a match, so1 == trueevaluates to true becausetrueis converted to1. The===type equality operator doesn’t do type conversions, so1 === trueevaluates to false because the values are of different types.