No, there is no difference.
If foo.bar
is not a primitive value then first valueOf
is called on it. If that still does not return a primitive value, toString
is called on it. If that still does not return a primitive value, an error is triggered.
In all this, the foo.bar
object is not aware in which context valueOf
or toString
are called. There is no way the object can differentiate between the two cases you mention. It does not even have to be one of those two.
Finally, there is no way to set a trap on the +
operator, so you could know its operands.
Here is a demo of how valueOf
and toString
are called in that order:
const foo = {
bar: {
valueOf() {
console.log('valueOf');
return this; // not a primitive value, so now toString will be called.
},
toString() {
console.log('toString');
return "1";
}
}
}
console.log(foo.bar + '');
console.log("====");
console.log('' + foo.bar);
String(foo.bar)
?String
variable could be overwritten.