Skip to content

Instantly share code, notes, and snippets.

@codemaster138
codemaster138 / number-to-array.md
Created Jan 23, 2022
Encode any number as a strange javascript array expression
View number-to-array.md

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!?).

View gist:dc4e364b0a8c8bdb4df8511e5c0d573a
### Keybase proof
I hereby claim:
* I am codemaster138 on github.
* I am jakesarjeant (https://keybase.io/jakesarjeant) on keybase.
* I have a public key ASDVydmVKLhYfYma_yb8SJy1wowTdasQEVOSP1ZWX6Jwawo
To claim this, I am signing this object: