Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I second @Ventero’s solution. If you want to, you can go into more detail as to how <code>+</code> converts its operands.</p> <p><strong>First step (§9.1):</strong> convert both operands to primitives (primitive values are <code>undefined</code>, <code>null</code>, booleans, numbers, strings; all other values are objects, including arrays and functions). If an operand is already primitive, you are done. If not, it is an object <code>obj</code> and the following steps are performed:</p> <ol> <li>Call <code>obj.valueOf()</code>. If it returns a primitive, you are done. Direct instances of <code>Object</code> and arrays return themselves, so you are not done yet.</li> <li>Call <code>obj.toString()</code>. If it returns a primitive, you are done. <code>{}</code> and <code>[]</code> both return a string, so you are done.</li> <li>Otherwise, throw a <code>TypeError</code>.</li> </ol> <p>For dates, step 1 and 2 are swapped. You can observe the conversion behavior as follows:</p> <pre><code>var obj = { valueOf: function () { console.log("valueOf"); return {}; // not a primitive }, toString: function () { console.log("toString"); return {}; // not a primitive } } </code></pre> <p>Interaction (<code>Number()</code> first converts to primitive then to number):</p> <pre><code>&gt; Number(obj) valueOf toString TypeError: Cannot convert object to primitive value </code></pre> <p><strong>Second step (§11.6.1):</strong> If one of the operands is a string, the other operand is also converted to string and the result is produced by concatenating two strings. Otherwise, both operands are converted to numbers and the result is produced by adding them.</p> <p>More detailed explanation of the conversion process: “<a href="http://www.2ality.com/2012/01/object-plus-object.html" rel="noreferrer">What is {} + {} in JavaScript?</a>”</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