Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Why does <code>(![]+[])[+!![]+[]]</code> produce "a"</p> <p>step by step: this is parsed in: <code>(![]+[])</code> and <code>[+!![]+[]]</code>. First bit was already explained by artemb: <code>[]</code> is an array. Negating it, <code>![]</code> evaluates to a boolean, <code>false</code> - that's just how <code>!</code> works when it is applied to something that is not <code>null</code> or undefined. Again as pointed out by artemb, appending this <code>+[]</code> forces the boolean to be converted to a string. That's because the <code>+</code> is a string concatenation operator. The boolean <code>false</code> is then converted to its string representation, <code>"false"</code>.</p> <p>Then, the second bit, <code>[+!![]+[]]</code>. First of all, the outer <code>[</code> and <code>]</code> serve to treat the preceding string, which we just dervived is equal to <code>"false"</code> as an array of characters. By putting an integer index inside the <code>[</code> and <code>]</code>, you get the character at a particular index. So what remains is <code>+!![]+[]</code> This consists of 4 pieces: <code>+</code>, <code>!![]</code>, <code>+</code> and <code>[]</code>. First <code>!![]</code> is evaluated. We already saw that <code>![]</code> is a boolean <code>false</code> so prepending another <code>!</code> negates it, and yields <code>true</code>. Next thing what happens is that the <code>+</code> in <code>+!![]</code> gets applied, and by applying <code>+</code> it converts the boolean <code>true</code> into the number representation, which is <code>1</code> (so <code>+true</code> is <code>1</code>) The <code>+[]</code> that follows makes a string again from that <code>1</code> yielding <code>"1"</code> but it does not really make sense, the shorter expression <code>(![]+[])[+!![]]</code> already produces <code>a</code>. Appending <code>+[]</code> doesn't hurt either, the resulting expression is simply <code>["1"]</code> instead of <code>[1]</code>. My hunch is that when <code>[]</code> is applied to an array, whatever is inside the <code>[]</code> will be coerced into a number, which for <code>"1"</code> would give <code>1</code> again. So either way, <code>+!![]+[]</code> evaluates to <code>1</code>, making the final expression: <code>"false"[1]</code> which is saying: gimme the character at index 1 from the string <code>"false"</code>, and since by default, arrays start at <code>0</code> in javascript, this is the second character of <code>"false"</code>, and <code>a</code>.</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