Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>We may refer to the specification and that's great and most accurate, but most of the cases can also be explained in a more comprehensible way with the following statements:</p> <ul> <li><code>+</code> and <code>-</code> operators work only with primitive values. More specifically <code>+</code>(addition) works with either strings or numbers, and <code>+</code>(unary) and <code>-</code>(subtraction and unary) works only with numbers.</li> <li>All native functions or operators that expect primitive value as argument, will first convert that argument to desired primitive type. It is done with <code>valueOf</code> or <code>toString</code>, which are available on any object. That's the reason why such functions or operators don't throw errors when invoked on objects.</li> </ul> <p>So we may say that:</p> <ul> <li><code>[] + []</code> is same as <code>String([]) + String([])</code> which is same as <code>'' + ''</code>. I mentioned above that <code>+</code>(addition) is also valid for numbers, but there is no valid number representation of an array in JavaScript, so addition of strings is used instead.</li> <li><code>[] + {}</code> is same as <code>String([]) + String({})</code> which is same as <code>'' + '[object Object]'</code></li> <li><code>{} + []</code>. This one deserves more explanation (see Ventero answer). In that case, curly braces are treated not as an object but as an empty block, so it turns out to be same as <code>+[]</code>. Unary <code>+</code> works only with numbers, so the implementation tries to get a number out of <code>[]</code>. First it tries <code>valueOf</code> which in the case of arrays returns the same object, so then it tries the last resort: conversion of a <code>toString</code> result to a number. We may write it as <code>+Number(String([]))</code> which is same as <code>+Number('')</code> which is same as <code>+0</code>.</li> <li><code>Array(16).join("wat" - 1)</code> subtraction <code>-</code> works only with numbers, so it's the same as: <code>Array(16).join(Number("wat") - 1)</code>, as <code>"wat"</code> can't be converted to a valid number. We receive <code>NaN</code>, and any arithmetic operation on <code>NaN</code> results with <code>NaN</code>, so we have: <code>Array(16).join(NaN)</code>.</li> </ul>
 

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