Javascript Simple Boolean Arithmetic

I heard about Boolean arithmetic and thought of trying to try.

alert (true+true===2)  //true
alert (true-true===0)  //true

So algebra tells me true = 1

alert (true===1)  //false :O

Can anyone explain why this is happening?

+4
source share
4 answers

===is a strict equality operator. Try it instead ==. true==1will be graded before true.

The strict equality operator ===considers only values ​​equal if they are of the same type. The smaller equality operator ==tries to convert values ​​of different types before comparing them with strict equality.

Case 1:

true===1, true boolean, 1 . , true===1 false.

2:

true+true===2 true-true===0 ( + ===. . ), .

(true+true===2) true+true 2. . .. (2==2) true.

+4

TYPE value ( === '), TRUE , 1. TRUE == 1, .

+1

first 2 , (true+true) (true-true), - "===", toNumber toPrimitive - , ( ),

enter image description here

, true + true 2

===, , , , , .

Thats all

+1

At the beginning you do bool + bool. The + operator takes precedence over the === operator, so it evaluates first. In this evaluation, he converts Booleans to their numerical forms. Run console.log(true + true);, and this will return 2. Since you are comparing the number 2 with the number 2, you get the return value true with strict equality.

When you simply compare true === 1, like everyone else, you compare the boolean true with number 1, which is not strictly equal.

+1
source

Source: https://habr.com/ru/post/1616160/


All Articles