Since +obj
requires a number, shouldn't it use the valueOf()
prototype for type conversion which returns the object.
It actually does call the valueOf
method. But since - as you say - it returns an object, not a primitive value, it is found useless. Then, the alternative is called: toString()
, which does return a primitive value that is subsequently cast to a number.
You can try
const obj1 = {
valueOf() { console.log("valueOf 1"); return this; },
toString() { console.log("toString 1"); return "1"; },
};
console.log(+obj1);
const obj2 = {
valueOf() { console.log("valueOf 2"); return 2; },
toString() { console.log("toString 2"); return "2"; },
};
console.log(+obj2);