I was recently browsing twitter when I found an interesting tweet claiming that "Any JS integer can be represented using only [
, ]
and +
". The tweet also showed the number 10 encoded as ++[+[]][+[]]+[+[]]
:
console.log( ++[+[]][+[]]+[+[]] ); // Logs '10'
This tweet intrigued me. Can really any javascript integer be represented in this way? I had to find out.
First, I tried to deconstruct the example value. The expression can be split into two main parts: ++[+[]][+[]]
and [+[]]
, connected by a +
addition operator. Running each individual expression in a javascript REPL showed that the first expression encodes the number 1
and the second the number 0
. For some strange reason that is beyond me, javascript decides that because of the way the expression is written, the two numbers should be treated as strings and concatenated instead of being added (Why, javascript, why!?).