JavaScript truthiness in boolean to numbers comparison
I'm new to JavaScript and I'm trying to learn it from internet resources. While I'm开发者_运维知识库 aware that there will plenty of cr*p material, one thing most people seemed to agree is the truthiness of things in JS (just to give a example go here)
Now I found this odd thing in my experiments:
(true == 2)
is false
. why?
As far as I know, 2
is a non zero number, so it should be evaluated as true
.
This is because when either operand of an equality operator is a number, in nearly all cases the other operand is converted to a number and then the result is compared. So you're ending up comparing 1
(converted from true
) with 2
, not true
with true
. The only exceptions to that rule are null
, undefined
, and objects whose default value (see off-topic below) is null
or undefined
; comparing a number to those returns false
(even though Number(null)
is 0
; don't ask).
Details in the specification, Section 11.9.3: "The Abstract Equality Comparison Algorithm". This was the text of that section as of ES 5.1, but that link is to the currently editor's draft (which is what each year's snapshot specification is based on) and there have been several :
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is the same as Type(y), then
- Return the result of performing Strict Equality Comparison x === y.
- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
NOTE: This step is replaced in section B.3.7.2.- If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
- If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
- If Type(x) is BigInt and Type(y) is String, then
- Let n be ! StringToBigInt(y).
- If n is NaN, return false.
- Return the result of the comparison x == n.
- If Type(x) is String and Type(y) is BigInt, return the result of the comparison y == x.
- If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
- If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
- If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return the result of the comparison x == ? ToPrimitive(y).
- If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return the result of the comparison ? ToPrimitive(x) == y.
- If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
- If x or y are any of NaN, +∞
精彩评论