Writing Strings with JavaScripts using only six minimal characters!

Today, I had a crazy feeling on making something related to security. I did have come across something that really baffled me. Writing the strings using just six minimal characters. Yes, using JavaScript, if you want to output any string, it can be done using just the following six characters:

  • [ and ] - Array Square Brackets.
  • ( and ) - Parentheses.
  • + and ! - Addition and Negation Operator.

Let's try the simplest example possible. I assume everyone knows the fact that if you are double negating anything, it is as equivalent to type-casting something to its respective boolean value. So, !! gets the boolean value of something, while ! gets the negated boolean value.

One example of it would be:

» []
« []
» ![]
« false
» !![]
« true

The above seems to be obvious. So, we get the truthy and falsy values of the evaluated code in the console. These are totally fine, but the one that baffled me was, those getting converted into string! Let's take the below code as an example.

» (!![] + [])
« "true"
» (![] + [])
» "false"

That's not the only thing it can do. We already have got the numbers in this way. And after an initial research, I came to know that this technique is called JSFuck, which is one of many Esoteric programming languages. To write as simple as "a", you can do this way:

  • "a" is available in "false". So doing "false"[1] will give a.
  • To obtain "false" from false, we can can concatenate with an empty array. false+[] becomes "false".
  • From the above, we can get the negation of an empty array is false. So, ![] is false.
  • Adding it with the empty array, gives us false as "false". So we have ![]+[].
  • Now we need 1. Adding a + in front of true becomes 1. So, we can do +!+[] to get 1 and we can wrap it inside an array to get [+!+[]].
  • Attaching the above to the first set of steps, we get: (![]+[])[+!+[]].
  • The other way to get 1 is by converting true into integer, which is adding a + in front of true this way +!![].
  • Second way of producing a is (![]+[])[+!![]].

Check out the WikiPedia page for JSFuck and also the demo page of JSFuck. Hope you enjoyed learning something new!

comments powered by Disqus