I recently saw a question: how do you declare
aso thata == 1 && a == 2 && a == 3returns true? You can tellamust be an object, but what method should it use? This exposed how weak my understanding was of type coercion with==, so I reviewed it.
Implicit type coercion with ==
If types differ, consider primitive and object types:
- Primitive types
- Number and string: string is converted to number
- Number and boolean: boolean is converted to number
- Object types
- If one is an object, it calls
valueOfandtoStringto convert to a primitive
- If one is an object, it calls
If you use === (strict equality), there is no type conversion.
The question
(a ==1 && a== 2 && a==3)===true
Once you understand the rules, the solution is straightforward.
const a = {
i: 1,
valueOf: function () {
return a.i++;
}
};
Summary
- This question tests implicit type coercion and is quite interesting.
- In real projects, we usually use strict equality === and enforce it with ESLint to avoid surprises.

