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
  • 4,347
  • 27
  • 39

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
  • 289,723
  • 53
  • 439
  • 496
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
  • 158,873
  • 26
  • 254
  • 302
0
alert( (""+true)[2] ); // shows "u"

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

What does this return?

alert( (''+[[]][[]]));
duncan
  • 31,401
  • 13
  • 78
  • 99