Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript the Definitive Guide: the confusion of steps of converting object to a string

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 a toString() 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 a valueOf() 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() or valueOf(), 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?

like image 649
zhenguoli Avatar asked Jul 18 '17 01:07

zhenguoli


1 Answers

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.

like image 195
Jonathan Holland Avatar answered Oct 13 '22 00:10

Jonathan Holland