4

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?

m0bi5
  • 8,900
  • 7
  • 33
  • 44
  • 1
    Possible duplicate of [What is exactly the meaning of "===" in javascript?](http://stackoverflow.com/questions/1029781/what-is-exactly-the-meaning-of-in-javascript) – mpromonet Dec 01 '15 at 19:03

4 Answers4

4

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

Vivek
  • 11,938
  • 19
  • 92
  • 127
1

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.

Lis
  • 555
  • 4
  • 26
1

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

enter image description here

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

Shailendra Sharma
  • 6,976
  • 2
  • 28
  • 48
  • sorry for that i was editing my answer that time, true+true is a expression, i have attached image to explain how boolean values convert during expression , have you got idea how it was working ? – Shailendra Sharma Nov 17 '15 at 07:24
1

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.

Sam
  • 1,115
  • 1
  • 8
  • 23