The Alert to Life, the Universe and Everything, Part 3 – There are no strings on me.

Hello again. In the last two posts we’ve been looking at this amazing piece of code and breaking it down, bit by bit:

[][(__=”+!!(_=+[]))[_$=-~-~-~_]+($$=”+{})[$=-~_]+($_=”+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(”+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+”(“+((($<<($<<$)^$)<<($<<$)^$)<<$)+”)”)()

This is valid JavaScript code that provides an alert with the number 42 in it. Now, those looking at this for the first time will have heart palpitations and scream to the high heavens “What the f[CENSORED]k is this sorcery?” But, if you’ve been following my blog for some time now and read through my last post in particular, you’ll know that we’ve been decoding various aspects of code, piece by piece. Last post, were focused our efforts on numbers. As a result, our crazy code above was converted to the following:

[][(__=”+!!(_=0))[_$=3]+($$=”+{})[$=1]+($_=”+!_)[1]+$_[0]][$$[5]+$$[1]+(”+Infinity)[1]+__[3]+$_[0]+$_[1]+$_[2]+$$[5]+$_[0]+$$[1]+$_[1]](__[1]+__[2]+$_[3]+$_[1]+$_[0]+”(“+42+”)”)()

which albeit, is a little more legible, doesn’t give the full gist of what’s being executed. So, let’s decode it further. We tackled numbers in the previous post. Today, we’re going to look at strings.

Looking at our semi-digested code here, we can spot a number of references to empty strings:

  • (__=”+!!(_=0))
  • ($$=”+{})
  • ($_=”+!_)
  • (”+Infinity)

And two references to non-empty strings, “(” and “)”. Let’s take a look at the four code examples above and see what they’re all about.

(__=”+!!(_=0)), self-encapsulated variable assignments so that the values can be used straight away, we already determined the value of _ in the previous post as zero. Now, we have the double-not operator operating on zero, which you may remember from my previous post coerces the operand (the zero) to its equivalent Boolean. As zero is a falsy value, !!0 is coerced to the Boolean false. So far, so good. Next to the newly determined false we have an empty string and a concatenation operator. This empty string and the concatenation operator serve one purpose and one purpose only – to coerce the object they’d act upon to a string representation of it. In the case of false, it gets coerced to the string “false”, the value for __. Let’s put it aside for now, and move onto the next piece of code.

($$=”+{}), also self-encapsulated for immediate use. But this time we have the empty string and concatenation operator dynamic duo acting upon an empty object. Objects are weird things, and so, accordingly, the result is about as weird; the string result is not “object”, but rather “[object Object]”. I currently do not have the reasons for why this is at the moment, but I promise I’ll have a look and let you readers know in a future post. Just check it out for yourself. So that’s the value of $$ sorted. We’ll put that aside as well, age move on.

($_=”+!_), once again, self-encapsulated for immediate use of the value. This is similar to our first piece of code, save for a single-not operator acting on the zero value held by the _ variable. As a result !0 coerces the zero to a Boolean first, false, before applying the not, which results in $_ equalling ”+true, which is again coerced to “true”, the string equivalent of the Boolean true. Moving on to our final piece of code.

(”+Infinity), self-encapsulated (sensing a pattern?)… But this time, no assignment, so this is a one-off. This is a simple conversion of the object name to a string, rather much like true and false are. So, long story short, this code is equivalent to “Infinity”, the string.

So, with our newly discovered strings, and hoisting the variables to the top, let’s see what were get when we plug those in:

[][‘false'[3]+(‘[object Object]’)[1]+’true'[1]+’true'[0]][‘[object Object]'[5]+'[object Object]'[1]+’Infinity'[1]+’false'[3]+’true'[0]+’true'[1]+’true'[2]+'[object Object]'[5]+’true'[0]+'[object Object]'[1]+’true'[1]](‘false'[1]+’false'[2]+’true'[3]+’true'[1]+’true'[0]+”(“+42+”)”)()
This makes it somewhat more legible, but a bit of a mouthful, as well as a bit repetitive in places. We still have these array references everywhere… I promised in my previous post I would reveal the mystery of these array references, and here it is – Strings, in the eyes of JavaScript, are arrays of single character strings. For example, in the string “string”, “string”[0] is the first character “s”, “string”[1] is the second character “t”, and so on. The only exception is where you try to get the nth character of an empty string, like ”[0], which logically comes back as undefined.

Strings, in the eyes of JavaScript, are arrays of single character strings.

Using this knowledge, if you plug and chug this into our updated code we get the following:

[][‘s’+’o’+’r’+’t’][‘c’+’o’+’n’+’s’+’t’+’r’+’u’+’c’+’t’+’o’+’r’](‘a’+’l’+’e’+’r’+’t’+”(“+42+”)”)()

which when we apply all the concatenation operators gives us:

[][‘sort’][‘constructor’](‘alert(42)’)()

Very legible, but the syntax is probably unfamiliar to you, But, if you were to run this you would still get your alert with 42; why is that?

Let’s look from left to right here.

You have an empty array [], followed by an array reference of “sort”. This is actually referring to the array object’s native method of sort. If you ran:

[2,1,3][“sort”]()

You would get the same result as if you had run:

[2,1,3].sort()

As non-alphanumeric JavaScript is unable to provide a way that would allow you to access methods or properties in dot format like x.y or x.y(), JavaScript has these alternative forms, x[“y”] and x[“y”]() available for you to use.

But note that a) we have an empty array in use, and b) we have a second chained array reference. Why is that? I’ll answer (b) first: x[“y”][“z”] is the same as x.y.z, so the more and more array references is equivalent to more and more dot references until you get to the property or method you are trying to access. In this case, you’re accessing the constructor property of the empty array’s sort method.

But here’s the thing, [][‘sort’][‘constructor’] gives rise to JavaScript’s native Function method on the window object:

function Function() { [native code] }

In fact, if you were to execute:

window.Function(“alert(42)”)()

You’d be doing the exact same thing as:

[][‘sort’][‘constructor’](‘alert(42)’)()

The Function method then takes the first parameter which is basically what we want it to do, and then the () ensures the execution.

You can conclude this is an alternative form of getting a JavaScript statement to execute. As to (a), the empty array is for simplicity.

So, given all this, let’s look into some other crazy crap that could be achieved this way. This concludes Part 3. There won’t be Part 4, but I promise to make the next few posts just as interesting. Until then, stay quirky!

The Alert to Life, the Universe and Everything, Part 2 – “Don’t Lose my Number”

So my previous post had this gorgeous monstrosity:

[][(__=”+!!(_=+[]))[_$=-~-~-~_]+($$=”+{})[$=-~_]+($_=”+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(”+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+”(“+((($<<($<<$)^$)<<($<<$)^$)<<$)+”)”)()

This code results in an alert with the number 42 in it…

So, how do we get from that code to 42? Well, as I said in my previous post, a lot of it deals with loose typing and some pretty cool math wizardry. I’m going to focus on the numerical side of things in this post so that we can see how we’re getting numbers when there are no numbers in sight.

Before I begin, I also mentioned in my previous post that some awesome variable naming conventions were being used. Take a look at the following instances that are present in the code:

  • _ (single underscore)
  • __ (double underscore)
  • $ (single dollar)
  • $$ (double dollar)
  • $_ (dollar underscore)
  • _$ (underscore dollar)

JavaScript accepts all these as valid variable names. If I were to restrict my definition to the ASCII subset of what’s valid, a valid JavaScript variable name can consist of any combination of numbers, lowercase and uppercase Latin letters, underscore and dollar sign, provided it doesn’t start with a number. The best full definition for valid JavaScript variable names can be found here.

So, because we have variable names in the code, the equal signs next to them are used for assignment.

So, now that we’ve established that, let’s focus on the numbers.

Firstly, we have the following snippet:

_=+[]

What’s the go with this, I hear you ask? Here, we’re assigning the value of _ to 0. To explain this, we need to establish what we already know about falsy values. Falsy values are what can be coerced to false when acted on by a Boolean operator. To determine whether a value or object is falsy, you apply the logical double-not operator on it and view the result. If the result is false then your original value is falsy. 0 is a falsy value, an empty string “” is falsy, and so is an empty array []. Applying the unary positive operator + on a falsy value coerces it to zero.

So _=+[] is identical to _=0.

You may have noticed this variable assignment its nested within another variable assignment:

(__=”+!!(_=+[]))

This is valid JavaScript. Granted, it’s not pretty, but it’s valid nonetheless. The purpose of doing this is so that the variable can be used at the time the variable is being defined. In this instance, __ is defined as an empty string concatenated to the double-not Boolean of 0. If you’ve read previous posts of my blog, you’d know that the double-not operator coerces the 0 to false, the Boolean value, and the empty string with the concatenation operator coerced that, in turn, to “false”, the string. But we’ll focus on the string parts in my next post.

The next variable assignment of interest is the following:

_$=-~-~-~_

Minus tilde, minus tilde, minus tilde… So it’s repeated three times, but what does that mean? Let’s look at the following:

-~0

We knew the underscore variable in our example was zero, so I’ve rendered it out as such. The tilde operator takes the number to the right of it, and performs the following algorithm on it -(N+1), then spurs back the result. In this example, ~0 is equal to -(0+1) = -1. Seems like a strange thing for an operator to do, but it works. So we have -1, but we also have the additional unary negative operator in front of it, do this coerces to -(-1) or 1. So technically -~N is the same as N+1.

So, that would mean that _$=-~-~-~_ is the same as _$=0+1+1+1 which means we’ve just written the equivalent of _$=3. Similarly, the $=-~_ reference in ($$=”+{})[$=-~_] is equivalent to $=1.

Next, we have the encapsulated statement in $$[-~($+_$)]. $+_$ based from the previous paragraphs is equivalent to 1 ($) plus 3 (_$) which is 4, but with the -~ operators, this raises it to 5. So this statement is the same as $[5].

Following this section there’s third little nugget…

$/_ … But if you do your substitutions that works out to be 1/0, which is mathematically infinite… Well, luckily, JavaScript has the Infinity value… We’ll address how Infinity comes into play in this code in the next post…

And the $+$ reference is simply 1+1 which is equal to 2.

Lastly, we have this “centrepiece” statement:

((($<<($<<$)^$)<<($<<$)^$)<<$)

This makes use of the number 1 (the value of $) over and over again… But why?

Here’s why, let’s substitute $ for one and see what we have.

(((1<<(1<<1)^1)<<(1<<1)^1)<<1)

Two operators here at work, the left-bitwise shift operator (<<) and the bitwise XOR operator (^).

Quick lesson on how these two work:

The bitwise left shift operator (we’ll call it the BLSO from here on) takes the number and shifts all bits one bit to the left. With each shift, you’re essentially doubling the number. The general formula is that X<<Y is equivalent to doubling X, Y times. So 5<<1 = 10, 5<<2 = 20 and so on. Bear in mind this works specifically for the integers party of your numbers only. If you executed 9.6<<1 your answer will be 18 not 19.2.

1<<1 is therefore 2 so let’s substitute it back in:

(((1<<2^1)<<2^1)<<1)

Note the section in bold: (1<<2^1), the BLSO takes precedence over the XOR operator, so we run it through again:

(((4^1)<<2^1)<<1)

So the XOR operator, what happens here? The XOR operator in this case compares the numbers bit by bit, and returns true if and only if the bit in both numbers are not identical, otherwise. 1 and 0? Return 1. 0 and 1? Return 1. 1 and 1 or 0 and 0? Return 0. So in our first case, 4^1, i.e. 4 XOR 1 I’d worked out as:

4: 100

1: 001

XOR: 101 = 5

This is a rather clever way of adding 1 to any multiple of 2 as any multiple of 2 will naturally have that 1’s bit (the one at the very right of a positive binary number) set to zero. So, 1<<1^1 is 3, 2<<3^1 is 17 and so on.

So let’s plug it and chug it over and over, using what we’ve learned and see what we get.

(((4^1)<<2^1)<<1)4^1 = 5

((5<<2^1)<<1) …5<<2 is 5×2×2 = 20

((20^1)<<1) …20^1 = 21

21<<1 …21<<1 = 42

We have our magical 42 popping up… So what’s the go with the rest of the code? This, my dear readers, is the code for the JavaScript alert, but we will get to that within the next few posts. Before I go, let’s take another look at that original code:

[][(__=”+!!(_=+[]))[_$=-~-~-~_]+($$=”+{})[$=-~_]+($_=”+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(”+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+”(“+((($<<($<<$)^$)<<($<<$)^$)<<$)+”)”)()

Now let’s take a look at that same code with all the numbers rendered out:

[][(__=”+!!(_=0))[_$=3]+($$=”+{})[$=1]+($_=”+!_)[1]+$_[0]][$$[5]+$$[1]+(”+Infinity)[1]+__[3]+$_[0]+$_[1]+$_[2]+$$[5]+$_[0]+$$[1]+$_[1]](__[1]+__[2]+$_[3]+$_[1]+$_[0]+”(“+42+”)”)()

A little more recognizable… But you’ve noticed we have a lot of array references here, yet no arrays have been created?

Well, they have, but not how you’d expect… I’ll tell you more in the next post, also entitled “I’ve got no strings on me”. Stay tuned!

The Alert to Life, the Universe and Everything… Part 1

I’m going to hit you with some supposed gobbledygook here…

[][(__=”+!!(_=+[]))[_$=-~-~-~_]+($$=”+{})[$=-~_]+($_=”+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(”+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+”(“+((($<<($<<$)^$)<<($<<$)^$)<<$)+”)”)()

Now, copy and paste it into your JavaScript console in your browser…

With me so far? Okay, now that you’ve pasted that, hit the Enter key on your keyboard.

You should get something similar to this:


An alert with 42 in it…

I showed this to a friend of mine who said in response “This is nuts!”

This was an entry of mine for a coding competition for displaying the number 42 on the most creative way thinkable.
This takes advantage of a lot of weird quirks of JavaScript like loose typing, alternative variable naming conventions, primitives and some really awesome bit mathematics. I’m going to go though these step by step over the next few posts.

Ready to be absolutely but happily mindf[CENSORED]ked? Okay, strap yourselves in, this is going to be a hell of a ride…

Stay tuned for Part 2, Don’t Lose My Number…