Since NaN is unequal to any other value, including to another NaN, why does not the looselyequal algorithm in Javascript Specification check if any one of the operands is NaN first? If any one of the operands is NaN, the result is false, no need more processing.
The following is the == algorithm in the Javascript specification:
- If SameType(x, y) is true, then
a. Return IsStrictlyEqual(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.6.2.
- If x is a Number and y is a String, return ! IsLooselyEqual(x, ! ToNumber(y)).
- If x is a String and y is a Number, return ! IsLooselyEqual(! ToNumber(x), y).
- If x is a BigInt and y is a String, then
a. Let n be StringToBigInt(y).
b. If n is undefined, return false.
c. Return ! IsLooselyEqual(x, n). - If x is a String and y is a BigInt, return ! IsLooselyEqual(y, x).
- If x is a Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
- If y is a Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
- If x is either a String, a Number, a BigInt, or a Symbol and y is an Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
- If x is an Object and y is either a String, a Number, a BigInt, or a Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
- If x is a BigInt and y is a Number, or if x is a Number and y is a BigInt, then
a. If x is not finite or y is not finite, return false.
b. If ℝ(x) = ℝ(y), return true; otherwise return false. - Return false.
According to this algorithm, if either x or y is NaN, step 5, 6, 9, 10, 11, 12 will cost running time, and the result must be false.
If the first step is:
1.if x or y is NaN, return false.
the algorithm can get and return this result immediately.