I have this code. And I don't understand how it works.
let obj = {
valueOf: function () {
return {};
},
toString: function () {
return 222;
}
};
console.log(Number(obj)); //222
According to this source, the conversion algorithm is:
- Call
obj[Symbol.toPrimitive](hint)
if the method exists,- Otherwise if hint is "string" try
obj.toString()
andobj.valueOf()
, whatever exists.- Otherwise if hint is "number" or "default" try
obj.valueOf()
andobj.toString()
, whatever exists.
Hint is number here. Then why is obj.toString()
called? Is there no obj.valueOf()
? Why? What kind of objects have this method? I can't find any useful information about this.
And here's another example:
var room = {
number: 777,
valueOf: function() { return this.number; },
toString: function() { return 255; }
};
console.log( +room ); // 777
Why is obj.valueOf()
called in this case? Why does this method exist here, and doesn't in the first example? How does it work?