Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - Why does !!1=="1" equal true and !!2=="2" equal false?

As the title states, why does:

> !!1=="1"

equal

True

and

> !!2=="2"

equal:

False

Likewise, why does > "1"==true equal true and > "2"==true equal false

I'm baffled. Are these just bugs in JS or what's going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per the Operator precedence rules, logical ! has higher priority over ==. So, in both the cases, !! is evaluated first.

Note: Truthiness of various objects have been explained in this answer of mine.

First Case

!!1 == "1"

!1 will be evaluated to false, since 1 is considered Truthy. Negating again we get true. So the expression becomes

true == "1"

Now, the coercion rules kick in as you have used == operator, which evaluates as per the The Abstract Equality Comparison Algorithm defined in ECMAScript 5.1 Specification,

6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

So, true will be converted to a number, which is 1 as per ToNumber algorithm for Boolean values. Now the expression becomes

1 == "1"

Now,

4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

So, "1" will be converted to a number and that will give 1, as per the ToNumber algorithm. That is why it shows true in the first case.

Second Case

The same rules are applied here.

!!2 == "2"

becomes

true == "2"

then

1 == "2"

which becomes

1 == 2

which is not true, that is why the second case prints false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...