7

I'm not sure what is happening in this line of javascript:

alert( (''+[][[]])[!+[]+!+[]] ); // shows "d"

What I've figured out:

var a = ! + []; // == true
var b = ! + [] + ! + []; // == 2

It seems that the second part is a reference into an array of letters or some sort, but I don't understand how that is coming from

(''+[][[]])

Also:

alert( (''+[][])[2] ); // nothing happens; console says "unexpected token ]"
alert( (''+[[]][])[2] ); // nothing happens; console says "unexpected token ]"
alert( (''+[[]][[]])[2] ); // shows "d"
alert( (""+true)[2] ); // shows "u"
BurnsBA
  • 2,890
  • 16
  • 29

3 Answers3

4

I'll decompose it for you:

  ('' + [][[]])[!+[]+!+[]]
= ('' + undefined)[!+[]+!+[]]  // [][[]] grabs the []th index of an empty array.
= 'undefined'[! + [] + ! + []]
= 'undefined'[(! + []) + (! + [])]
= 'undefined'[true + true]
= 'undefined'[2]
= 'd'

! + [] == true is explained here What's the significant use of unary plus and minus operators?

Community
  • 1
  • 1
Blender
  • 257,973
  • 46
  • 399
  • 459
2

Because "" + true is the string "true", and the third character (index 2) is u.

Things like ! + [] work because + can also be a unary operator, see this SO question.

Community
  • 1
  • 1
Dave Newton
  • 152,765
  • 23
  • 240
  • 286
0
alert( (""+true)[2] ); // shows "u"

It's returning the 3rd letter of the string "true".

What does this return?

alert( (''+[[]][[]]));
duncan
  • 29,669
  • 9
  • 70
  • 93