Ahmad Alfy
Ahmad Alfy

Reputation: 13371

Why converting an integer to truthy value works differently when using comparison operator vs using !! in JavaScript

Why this returns false

2 == true

While this return true

!!2

I couldn't find a proper explanation. I was surprised cause I thought both behave the same.

Upvotes: 2

Views: 86

Answers (2)

nnnnnn
nnnnnn

Reputation: 150070

The == operator first converts its operands to the same type (if they're not already), and then compares the resulting values. In the case of 2 == true, it converts true to be a number, which results in the value 1. And of course 2 == 1 is false.

There is no !! operator, that is just the ! operator used twice in a row. So !!2 is actually doing !(!2), i.e., it first evaluates !2 to get false, and then evaluates !false, resulting in true. In other words, using !! converts any truthy value to be the actual boolean value true.

Note that all non-zero numbers are "truthy", so !anyNumberButZero will be false. (NaN is a special case: !NaN is true.)

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122018

In case 1, When you do 2 == true it tries to convert the checks for the value 2 equals to true or not. Hence the false. This applies only for the values above 1.

From docs of ==

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

Since you comparing 2 against boolean true, and true converts to 1. Hence 2==1 resolved to false.

However when you do if(2) checks if it is truthy or not. Since it is trurthy, you did !! becomes truthy again.

Examples of truthy values in JavaScript (which will translate to true and thus execute the if block):

if (true)
if ({})
if ([])
if (42) . // your case

Upvotes: 1

Related Questions