Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's a bit more complex.</p> <p>You'll find a very good explanation how it works here: <a href="http://www.adequatelygood.com/2010/3/Object-to-Primitive-Conversions-in-JavaScript" rel="nofollow noreferrer">http://www.adequatelygood.com/2010/3/Object-to-Primitive-Conversions-in-JavaScript</a></p> <p>But it seems the way ben cherry described did changed (also what I regonized). If you will run his example:</p> <pre><code>function population(country, pop) { return { country: country, pop: pop, toString: function () { return "[Population " + "\"" + country + "\" " + pop + "]"; }, valueOf: function () { return pop; } }; } var america_pop = population("USA", 350e6); var mexico_pop = population("Mexico", 200e6); var canada_pop = population("Canada", 200e6); alert(america_pop); // [Population "USA" 350000000 var north_america_pop = america_pop + mexico_pop + canada_pop; alert(north_america_pop); // 750000000 </code></pre> <p>This isn't true anymore, the alerts will be:<br> 350000000<br> 750000000</p> <p>alert(obj) call valueOf() not toString() anymore, execpt if you use Array.join</p> <pre><code>alert([america_pop]); // [Population "USA" 350000000 </code></pre> <p>There was already a thread about: <a href="https://stackoverflow.com/questions/2485632/valueof-vs-tostring-in-javascript">valueOf() vs. toString() in Javascript</a></p> <p>They clearify that, valueOf is always called when [hint] is a number and that's always the case, except if you join an Array. that's confusing, because if you call 'string' + 'string' this is definitely a string context, but JS will first take look at the number context, and call always the valueOf() method not toString() if it's a primitive value</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload