Coercion in javascript?

In the below code coercion is happening alright , but == operators need booleans to compare so coerced string potato will return true , then true == true it has to return true right but why its returning false.

 console.log("potato" == true);  //false

That’s an incorrect assumption. When you check the ECMAScript specification, you’ll find a whole different algorithm: (cf. https://www.ecma-international.org/ecma-262/6.0/index.html#sec-abstract-equality-comparison)

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

1. ReturnIfAbrupt(x).
2. ReturnIfAbrupt(y).
3. If Type(x) is the same as Type(y), then
    Return the result of performing Strict Equality Comparison x === y.
4. If x is null and y is undefined, return true.
5. If x is undefined and y is null, return true.
6. If Type(x) is Number and Type(y) is String,
    return the result of the comparison x == ToNumber(y).
7. If Type(x) is String and Type(y) is Number,
    return the result of the comparison ToNumber(x) == y.
8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
    return the result of the comparison x == ToPrimitive(y).
11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
    return the result of the comparison ToPrimitive(x) == y.
12. Return false.

For your case step 9 is applied ( 'potato' == 1), and subsequently step 7 ( NaN == 1) and step 3 (NaN === 1).

1 Like

Ok.i got it

The trouble with understanding double equals is why the triple equals was invented. Best practice is to just use triple equals to prevent all of the confusion from happening.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.