Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Simple Boolean Arithemetic

Tags:

javascript

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?

like image 320
m0bi5 Avatar asked Mar 15 '23 03:03

m0bi5


2 Answers

=== 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.

like image 180
Vivek Avatar answered Mar 23 '23 01:03

Vivek


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.

like image 23
Lis Avatar answered Mar 23 '23 01:03

Lis