You-dont-know-js: Coercion: Question about coercion using ==

Created on 22 Feb 2018  路  1Comment  路  Source: getify/You-Dont-Know-JS

Why would a scenario like "0" == null produce false given that == tries to coerce the operands to number before making the comparison?
If I do Number("0") and Number(null) both of them return 0. Then why does the comparison return a false?

Similarly
-> "0"="" // false how? when Number("") returns 0.
-> false == null
-> "" == null
-> 0 == null

Most helpful comment

"0"="" // false how? when Number("") returns 0.

when both sides are of the same type (strings) in this case, it's just ===, which in this case just does a straight string comparison.

"0" == null
false == null
"" == null
0 == null

The misconception here is that not all coercion steps result in ToNumber(..) conversion, only some of them. And even then, only if the case matches that step's condition. If you read through the steps of Abstract Equality Comparison, you'll see that none of these 4 cases matches any of steps 1-9, so they all fall through to step 10, which says to return false. Specifically, there's no step that matches for null on one side unless the other side is undefined.

>All comments

"0"="" // false how? when Number("") returns 0.

when both sides are of the same type (strings) in this case, it's just ===, which in this case just does a straight string comparison.

"0" == null
false == null
"" == null
0 == null

The misconception here is that not all coercion steps result in ToNumber(..) conversion, only some of them. And even then, only if the case matches that step's condition. If you read through the steps of Abstract Equality Comparison, you'll see that none of these 4 cases matches any of steps 1-9, so they all fall through to step 10, which says to return false. Specifically, there's no step that matches for null on one side unless the other side is undefined.

Was this page helpful?
0 / 5 - 0 ratings