According to the section 3.8.3 in the book Javascript the Definitive Guide 6th edition:
To convert an object to a string, JavaScript takes these steps:
• If the object has atoString()
method, JavaScript calls it. If it returns a primitive value, JavaScript converts that value to a string (if it is not already a string) and returns the result of that conversion. Note that primitive-to-string conversions are all well-defined in Table 3-2.• If the object has no
toString()
method, or if that method does not return a primitive value, then JavaScript looks for avalueOf()
method. If the method exists, JavaScript calls it. If the return value is a primitive, JavaScript converts that value to a string (if it is not already) and returns the converted value.• Otherwise, JavaScript cannot obtain a primitive value from either
toString()
orvalueOf()
, so it throws a TypeError.
For example:
var obj = {
toString: function() {
console.log('toStirng...');
return 90;
},
valueOf: function() {
console.log('valueOf...');
return 80;
}
}
console.log(obj + '');
Accordingly, the code snippet above will convert obj
to string because of obj + ''
, so it should print:
toString...
90
But actually, it prints:
valueOf...
80
So what's wrong? Doesn't obj + ''
convert obj
to string?
As illustrated nicely in this article:
it is because +'' utilises the ToPrimitive(Number) internal method. If you run String(obj) you will receive the toString method result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With