Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an array reference into an empty string + true a valid character in JavaScript?

Tags:

javascript

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"
like image 862
BurnsBA Avatar asked Jun 17 '12 20:06

BurnsBA


1 Answers

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?

like image 166
Blender Avatar answered Oct 08 '22 12:10

Blender