I’ve heard of boolean arithmetic and thought of giving it a try.
alert (true+true===2) //true
alert (true-true===0) //true
So algebra tells me true=1
alert (true===1) //false :O
Could someone explain why this happens?
I’ve heard of boolean arithmetic and thought of giving it a try.
alert (true+true===2) //true
alert (true-true===0) //true
So algebra tells me true=1
alert (true===1) //false :O
Could someone explain why this happens?
===
is the strict equality operator. Try ==
operator instead.
true==1
will evaluate to true
.
The strict equality operator
===
only considers values equal if they have the same type. The lenient equality operator==
tries to convert values of different types, before comparing like strict equality.
Case 1:
In case of true===1
, The data type of true is boolean whereas the type of 1 is number. Thus the expression true===1
will evaluate to false
.
Case 2:
In case of true+true===2
and true-true===0
the arithmetic operation is performed first(Since +
operator takes precedence over ===
. See Operator Precedence) and then the result is compared with the other operand.
While evaluating expression (true+true===2)
, the arithmetic operation true+true
performed first producing result 2. Then the result is compered with the other operand. i.e. (2==2)
will evaluate to true
.
Because comparing data TYPE and value (that's what operator '===' does ), TRUE is not exactly the same as 1. If you changed this to TRUE == 1, it should work fine.
first 2 expression are true because you are using expression (true+true)
(true-true)
it convert type of a value first due to expression and check equality with "===", toNumber
and toPrimitive
are internal methods which convert their arguments (during expression ) this is how conversion take place during expression
That's why true+true equal to the 2
In your third expression you are using === this not convert arguments just check equality with type, to make it true both values and there type must be same.
Thats all
At the beginning, you're doing bool + bool. The + operator takes precedence over the === operator so it's evaluated first. In this evaluation, it's converting the booleans to their number forms. Run console.log(true + true);
and this will return 2. Since you're comparing the number 2 to the number 2, you get a return value true with the strict equality.
When you're just comparing true === 1
, like everyone else said you're comparing the boolean true to the number 1 which is not strictly equal.