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?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@SOReadytoHelp Edited my answer. Have a look.
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.

Comments

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.

Comments

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

1 Comment

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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.