How / why does this javascript code print “fun”?

alert( (![]+[])[[]-[]]+ (([]+[])+([][[]]))[[]-[]]+ (([]+[])+([][[]]))[!![]-[]] ); 

Heres the fiddle: http://jsfiddle.net/leeny/6VugZ/

How exactly does this cryptic piece of code work?

+7
source share
1 answer
  vvvvvvv [0] (![]+[])[[]-[]] = "false"[0] ^^^^^^^^ "false" vvvvvvv again [0] (([]+[])+([][[]]))[[]-[]] = "undefined"[0] ^^^^^^^^^^^^^^^^^^ "undefined" vvvvvvvvv this time [1] (([]+[])+([][[]]))[!![]-[]] = "undefined"[1] ^^^^^^^^^^^^^^^^^^ again "undefined" 

So you get "f"+"u"+"n" === "fun" .

Further explanation

"false"

![] - false . +[] just acts like converting to a string. Thus, we get the string "false" .

"undefined"

One of the operands must be a string. This is done using []+[] . The actual undefined is created on the right side: [][[]] === [][0] , the first record of an empty undefined array.

+7
source

All Articles