While reading this article posted on dzone I found a snippet of JavaScript originally posted on Twitter by Marcus Lagergren.

The following code apparently prints the string "fail"

(![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]];

This involves implicit type casting and I'm trying to understand how exactly this line is interpreted.

I've isolated each character

  • (![]+[])[+[]] prints "f"
  • (![]+[])[+!+[]] prints "a"
  • ([![]]+[][[]])[+!+[]+[+[]]] prints "i"
  • (![]+[])[!+[]+!+[]] prints "l"

I've also managed to break down the expressions returning each letter apart from "i"

letter "f"

![] an empty array is an Object, which according to ECMAScript documentation, point 9.2 evaluates to true when converted to a boolean so this is false

false+[] as per Point 11.6.1 both arguments of the binary + operator get converted to String, therefore we get "false"+"", which evaluates "false"

+[] a unary plus operator causes a ToNumber conversion followed by a ToPrimitive conversion if the argument is an Object. The result of such conversion is determined by calling the [[DefaultValue]] internal method of the object. In case of an empty array, it defaults to 0. (ECMAScript Documentation, sections: javascript types obfuscation ecmascript-5

Edit
Report