If Var A = True Then A == 1 Is True But A == 2 Is False. Why?
Solution 1:
Why? I understand that in javascript boolean expressions 0 casts to false and 1 casts to true.
Because Number(true)
=> 1
As per spec of abstract equality expression evaluation
- If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
Hence a
is first coerced into a Number and then compared with 1.
Solution 2:
when you use == or != in js,the operands will be converted to the same type before making the comparison.when converting:
if there is a Boolean, true will be turned to 1 and false turned to 0;
var a = true;
a == 1;// a turned to 1 before compare,so true
a == 2;// a turned to 1 before compare,so false
Solution 3:
This is to do with coercion. In the a == 1
scenario, a
is coerced into a an integer to compare again 1, true
is coerced to 1
. In the second example, a
is again coerced to 1
, so it doesn't equal 2
.
Solution 4:
You may convert 1
to True
and True
to 1
but you can't convert other numerics to True
.
Solution 5:
That's probably inherited from binary world and it makes sense, because in binary 0 is false and 1 is true. Exactly, that is how type conversion been done for boolean types in javascript as well while comparing.
For boolean there are only 2 possibles, true
or false
. Hence in number/binary system 0 and 1 are apt to represent them.
Post a Comment for "If Var A = True Then A == 1 Is True But A == 2 Is False. Why?"