#25: A custom valueOf() in == comparisons
Topic: coercion · Difficulty: ★★
const obj = { valueOf() { return 42; } };
console.log(obj == 42);
console.log(obj == '42');Output
true true
Why
When == compares an object against a primitive, it converts the object to a primitive using ToPrimitive, which by default calls the object's valueOf() method before falling back to toString(). Here obj.valueOf() returns 42, so the object effectively becomes the number 42 for the comparison. obj == 42 is then just 42 == 42, true. obj == '42' also calls valueOf() first (numeric hint), getting 42, then compares 42 == '42', which coerces the string to a number and is also true.
More coercion puzzles