Sine here… and here… and here…

Readers, I screwed up royally… I had published this post yesterday, only to accidentally overwrite it this morning. Add to that not having backed it up makes me a silly little programmer/blogger… So I’m going to write this out again, but this time, the way it should have been done, along with backing it up just in case I stupidly do this again.

So, last week we touched upon the derivation of a square root function that relied on nothing but fat arrow functions and standard operators – no reserved words, no native methods, no JavaScript libraries, nothing fancy whatsoever. We used Newton’s method of approximation to get closer and closer to the value, and we succeeded in doing so. We even streamlined it so that it looked pretty bad-ass…

Today I want to touch upon applying a similar technique to replicating the three basic trigonometric functions found in JavaScript’s Math library, but rendering them (as in our previous post) such that they are also void of any reserved words, native methods, or JavaScript libraries – just straight off fat arrow functions and standard operators. The three I want to focus on are:

  • The sine function, Math.sin();
  • The cosine function, Math.cos(); and
  • The tangent function, Math.tan()

We’ll tackle them in this order as there is a natural progression from the first to the last function. So let’s start off with the sine function.

Sine Function

The sine function has been determined to be a sum of terms, as discovered by the Taylor series. The Taylor series for the sine function is as follows:

As you can see there’s two particular mathematical functions at play with the derived sum:

  • The factorial, indicated by the (2n+1)! Component; and
  • The exponentiation or power, indicated by both (-1)n and x2n+1.

We can replicate both functions as recursive JavaScript functions that we can call upon later:

_fac = x => x < 2 ? 1 : x * _fac(x - 1);
_pow = (x, y) => y-- ? x * _pow(x, y) : 1;

Note that both of these functions are based solely on integer calculations, so no 3.4! or 2.53.1 happening here – there’s no need for this with what we’re trying to do today.

From these two functions and the value of a single term of the sine Taylor series, you can derive the following:

S = (x,n) => _pow(-1, n) * _pow(x, 2 * n + 1) / _fac(2 * n + 1)

Now, we need to just add the first n terms, wait a second, we’re talking an infinite number of terms! Let’s approximate that. I’ve performed enough testing to verify that the first 100 terms should be enough. Technically, it’s actually overkill after the first 14 or so terms, but depending on the system calculating the several decimal places, after 100 terms, you’re dealing with zero underflow because the value of the later n terms converge so close to zero that the system treats these values as zero because it can’t think that small. Anyhow, here’s the function, implementing the code for the single terms of the sine Taylor series, all added up:

_sin = function(x) {
    for(n = 100, z = 0; ~(--n); z += _pow(-1, n) / _fac(2 * n + 1) * _pow(x, 2 * n + 1));
     return z;
}

Two things to note in this function:

  1. The ~(–n) component. This is a creative way to use a loop from n to 0, and also decrement at the same time after each execution prior to the condition test. The tilde is a bitwise NOT operator (BNO) which applies the following algorithm:
    1. Take N, and add 1;
    2. Negate the result
    3. Return the result
    4. Put simply it applies –(N+1) to the value provided, so ~6 becomes -7, for example. Towards the end of the loop, counting down from 100 to 0, the application of the BNO on 3, 2, 1, 0 yields -4, -3, -2, -1, which are all truthy values, so the loop continues. It is only after then when n reaches ‑1, ~(-1) becomes –(-1+1) = 0, a falsy value, and so the loop stops.
  2. We’ve moved the actual actions of the for loop into the last parameter. This works well as it allows us to chain a lot of stuff up within the for loop. I’ll touch on this in a later post.

This is great, but that for loop is a little nasty… How about we make this a recursive function and hoist n and z up into the parameter section?

_sin = (x, n = 100, z = 0) => ~--n ? _sin(x, n, z +_pow(-1, n) / _fac(2 * n + 1) * _pow(x, 2 * n + 1)) : z;

What have we done exactly? We’ve hoisted up the n and z values, and set their defaults, seeing the first iteration of the function only calls on x. We’ve also ensured that in later iterations that n and z are called. We’ve removed the parentheses from the ternary function’s condition as it’s not necessary given the nature of the condition. Also the value of z being passed is already defined as z plus the next Taylor series term, so we don’t need to re-assign it back to z as it’s already done when we recurse. Finally, if the condition becomes falsy, the value of z passed into the function is the value returned. By that stage we should have converged on the value of sin(x) to the best of the compiler’s ability.

We can go further with this… Remember what I said about the BNO?

~n = -(n+1)

So if we were to negate both sides, we’d get:

-~n = n+1, which makes sense as -~6 would make 7. This means to increase a number by one, we can stick -~ in front of it…

We technically can then add n to both sides and get

n-~n = 2n+1… Look familiar? We have it in twice in our code, as 2 * n + 1. So let’s substitute and re-write the code:

_sin = (x, n = 100, z = 0) => ~--n ? _sin(x, n, z +_pow(-1, n) / _fac(n-~n) * _pow(x, n-~n)) : z;

That looks gorgeous… But how does that rate against the real deal, i.e. Math.sin(x)?

Let’s test this against four values of x:

  • π radians (180 degrees), sin π = 0
  • π/2 radians (90 degrees), sin π/2 = 1
  • π/3 radians (60 degrees), sin π/3 = √(3)/2 = 0.866025403…
  • π/4 radians (45 degrees), sin π/4 = √(2)/2 = 0.707106781…

Let’s get testing:

Test 1

_sin(π) = 0

Math.sin(π) = 1.2246467991473532e-16

Note that JavaScript’s native library can’t hack it here… It’s hit 0.00000000000000012246467991473532 but gives up, as though it hasn’t gone far enough. If it was indeed using a similar approach to what we’ve used, it doesn’t appear to have done enough iterations. I’ve done a little tinkering with the default value of n in our _sin() function, and determined that once we hit 14 iterations, _sin(π) hits zero underflow and coerces to zero. Anything fewer than that, and you get something similar to JavaScript’s attempt.

Winner: _sin()

Test 2

_sin(π/2) = 1

Math.sin(π/2) = 1

Both seem to have handled it, so let’s call this a tie.

Winner: TIE

Test 3

_sin(π/3) = 0.8660254037844386

Math.sin(π/3) = 0.8660254037844386

Again, a tie… both are returning the expected value.

Winner: TIE

Test 4

_sin(π/4) = 0.7071067811865475

Math.sin(π/4) = 0.7071067811865475

Yet again, another tie… both are returning the expected value.

Winner: TIE

Overall winner: _sin()

This is great! Could we apply a similar result with the cosine function equivalent? Let’s take a look…

Cosine Function

The cosine function has a similar formula, based off the Taylor series. This is what the Taylor series says about the cosine function:

Almost identical, save that any instance of 2n+1 is replaced with just 2n. if that’s the case, we can derive the _cos() function quite readily:

_cos = (x, n = 100, z = 0) => ~--n ? _cos(x, n, z +_pow(-1, n) / _fac(2*n) * _pow(x, 2*n)) : z;

Let’s test this out with the same tests as before, remembering we’ll get different results with cosines:

  • π radians (180 degrees), sin π = -1
  • π/2 radians (90 degrees), sin π/2 = 0
  • π/3 radians (60 degrees), sin π/3 = 0.5
  • π/4 radians (45 degrees), sin π/4 = √(2)/2 = 0.707106781…

Test 1

_cos(π) = -1.0000000000000009

Math.cos(π) = -1

Yuck… our function loses out here. Even if we stretch the number of iterations to twice what we have defined here, zero underflow does not kick in… JavaScript’s native library wins out this time.

Winner: Math.cos()

Test 2

_cos(π/2) = 0

Math.cos(π/2) = 6.123233995736766e-17

Native library has lost out this time, returning 0.00000000000000006123233995736766 and not hitting zero underflow, like how our derived function has.

Winner: _cos()

Test 3

_cos(π/3) = 0.5000000000000001

Math.cos(π/3) = 0.5000000000000001

A tie… Even though the result returned by both functions has an error of 5 × 10-15­­ %. Not ideal, but “acceptable”… kinda… Zero underflow has not been kind to either of these…

Winner: TIE, with caveats.

Test 4

_cos(π/4) = 0.7071067811865475

Math.cos(π/4) = 0.7071067811865476

Practically another tie… both are returning the expected value, well one of them is closer to the other… by about 1.4 × 10-14­­ %… WolframAlpha states that √(2)/2 = 0.7071067811865475244… And thus the derived function wins out.

Winner: _cos()

Overall winner: _cos()

So aside from the slight deviations by 14 to 15 orders of magnitude, _cos() has a strong case… Let’s take a look at the tangent function…

Tangent Function

This is even easier, because the tangent of an angle is equal to the sine of the angle divided by the cosine of the angle, we can define the function like this:

_tan = x => _sin(x) / _cos(x);

Let’s see how it stacks up with our tests…

  • π radians (180 degrees), tan π = 0
  • π/2 radians (90 degrees), tan π/2 = ∞ as sin(π/2) = 1, cos(π/2) = 0
  • π/3 radians (60 degrees), tan π/3 = √(3)
  • π/4 radians (45 degrees), tan π/4 = 1

Test 1

_tan(π) = 0

Math.tan(π) = -1.2246467991473532e-16

JavaScript Math library, go home, you’re drunk… Once again, the native method fails, returning ‑0.00000000000000012246467991473532 and can’t even hit zero underflow. Meanwhile our derived function has it all worked out…

Winner: _tan()

Test 2

_tan(π/2) = Infinity

Math.tan(π/2) = 16331239353195370

The native method has lost big time, returning a ridiculously high number, which is basically the reciprocal of Math.cos(π/2), seeing the Math.sin(π/2) returned 1 correctly. The returned value of 1/0.00000000000000006123233995736766 has made me question the validity of the JavaScript Math library. Meantime, our derived function hits the mark perfectly seeing it correctly gave us the correct values for _sin(π/2) and _cos(π/2).

Winner: _tan()

Test 3

_cos(π/3) = 1.7320508075688767

Math.cos(π/3) = 1.7320508075688767

A tie… Even though the result returned by both functions is off from the square root of 3 by has an error of about 3.4 × 10-14­­ %. Not ideal, but also “acceptable”…

Winner: TIE, with caveats.

Test 4

_cos(π/4) = 1

Math.cos(π/4) = 0.9999999999999999

Practically another tie… But the derived function wins as the native method keels over as it can’t tick over to the 1 mark… The JavaScript library is really letting me down here… Must have been that slight deviation from Math.cos() that put it out of whack…

Winner: _tan()

Overall winner: _tan()

So, what have we learned? Our derived functions seem to be more reliable than the existing JavaScript Math library… Could it be because we’ve established an algorithm that’s correctly executed ad absurdum? I’m honestly not sure what the answer is, but as far as we can tell, it seems more likely this is more accurate, by far.

My next post will be focusing on the derivation of two well-known irrational numbers, π and e using the same methodology. Until then, please stay quirky!

Advertisements

Getting to the root of the problem… Square root that is…

Last post I promised that my next few posts would kick it up a notch. I won’t let you down…

One thing I like to do to push the limits of my programming knowledge and think outside the box is to create functions that replicate native methods, without using native methods or reserved words to achieve the goal; so strictly operators only.

I’ve taken a rather bold example for my first example here, the calculation of a square root of a number.

The calculation of square roots has been done time and time again over the centuries. One of the well known methods for calculating a square root is called “Newton’s Method”, and its usage extends to the derivation of roots for any polynomial.

The function that governs square root calculation using Newton’s Method is:

f(x+1) = f(x) – (f(x)² – A)/(2 × f(x))

Where f(x) is the previous term, f(x+1) is the new term, and A is the original number being square-rooted. This is a recursive process, starting with f(0) = A. Once you start plugging in the values, getting your next term and plugging that in, over and over, you’ll find that the value of f(x+1) converges slowly to the square root of A. With each iteration, the value of (f(x)² – A)/(2 × f(x)) gets smaller and smaller until it reaches zero. Put simply, this expression is our “error factor”.

I like this process as it can be readily replicated in JavaScript. Bear in mind first, that my initial draft of the function below is just that, an initial draft. We will be taking a look at its evolution in this post to something more compact.

z=(x,y)=>

((y=y||x)*y-x)/(2*y)>1e-15?

z(x,y-(y*y-x)/(2*y)):y

So what have we done here? Let’s go through step-by-step.

Firstly, this function takes two parameters, with the initial function being called with one parameter, for example, z(37) to get the square root of 37. The reason behind using two parameters is during subsequent iterations of the function it calls two parameters, x, the value of the original number being passed, and y, a number getting closer to the square root of x with each iteration.

Recursion is one of the only few ways to perform this algorithm because you’re essentially performing the same process over and over until a certain amount of acceptable accuracy is reached. Depending on the value of x passed through one could potentially get a “Maximum Call Stack Size Exceeded” error from all the nested loops caused by said recursion.

Given the upper bound limits within JavaScript, my testing has shown that this starts losing cohesion at about z(1E140), i.e. the square root of 1 followed by 140 zeroes… We should potentially see an answer of “1e+70”, but what we do end up getting is 9.999999999999999e+69. Given the limit of available decimal places this ain’t bad, but what are the chances that you’ll be playing with numbers that large? By comparison, with reference to MarketWatch.com, as of September 15, this year, the US national debt stands at just over 20 trillion (20E+12) dollars [source], but I digress.

Remember when I mentioned that the value of f(0) was A, our initial parameter being passed when starting the Newton’s Method algorithm? This is being implemented in the initial part of our function as (y=y||x). This ensures that when we kick off the first iteration of z, that we have a value for y to play with by defaulting to our original number, and taking on the available value of y in subsequent iterations.

Next, as it can be seen, we’re using a ternary operator here, this is the ?: operator. Ternary operators are pretty damn cool in my opinion. They’re basically a shortcut way of expressing an if-then-else statement. They take on the form _condition?_if_true:_if_false. If condition _condition is met, then the statement _if_true prevails, else the statement _if_false prevails. For example, with age>=18?”Can vote”:”Cannot vote” if the age passed is 18 or over, the returned value is “Can vote”, otherwise the returned value becomes “Cannot vote”.

In this case we’re comparing the value of ((y=y||x)*y-x)/(2*y) with 1e-15, or 0.000000000000001… Tiny number. So we’re simply seeing how low our error factor is. Bear in mind, I had actually been using this to determine z(37) when I was initially testing this, so an error of 1e-15 seemed like a good idea at the time especially considering I compared it to the value of Math.sqrt(37). I then later realized I needed to reduce it down to practically zero, but we’ll address that later in this post.

If the ternary condition is true, i.e. the error factor is still to large to be deemed acceptable, the function runs another iteration of itself, but passes x as well as y minus the error factor, thereby getting closer to the original answer, and thereby reducing the error factor closer to zero. If the error factor is deemed sufficiently low, it returns the value of y, our square root.

Let’s reduce it further… As ES6 allows parameters to take on defaults we can shift the default short circuit of (y=y||x) and place it within the parameter component of our function. Now it becomes:

z=(x,y=x)=>

(y=(y*y-x)/(2*y))>1e-15?

z(x,y-(y*y-x)/(2*y)):y

Notice now we have two instances of (y*y-x)/(2*y), so let’s introduce a new variable k which will act as a marker, taking on x as a default and also take advantage of the fact that if you reduce a number small enough in JavaScript that it will coerce that number to zero… This is a phenomenon that’s known as zero underflow. This is where the number gets so small the JavaScript compiler throws up its hands and goes “You know what? That’s close enough to zero for me, I’m gonna call it zero” and runs with it… As a result, you get this:

z=(x,y=k=x)=>

(k/=2)?z(x,y-(y*y-x)/(2*y)):y

We’re using a divisor of 2 here so we can get as many iterations as possible and it also links nicely with our divisor in our second parameter in the recursed call. We can narrow this further. Let’s take a look at that second parameter in the recursive call: y-(y*y-x)/(2*y). A bit messy, but some simple algebra and a little JavaScript shortcutting can shorten this up.

y-(y*y-x)/(2*y)

Let’s rewrite this in algebraic form for ease of manipulation…

y – (y² – x)/2y

Let’s expand this, remembering that if you’re subtracting a negative, you’re actually adding a positive…

2y²/2y – y²/2y + x/2y

Which narrows down to:

y²/2y + x/2y

Which, in turn, narrows down to:

y/2 + x/2y

Which can also be expressed as:

y/2+x/2/y

Which can then be thrust back into our function:

z=(x,y=k=x)=>(k/=2)?z(x,y/2+x/2/y):y

Pretty sleek if you ask me… As you can see, this has taken away our need for an accuracy check as each iteration will persist until we hit that zero underflow I talked about earlier, which by that stage y will have reached a close enough value to the square root of x.

One final caveat here, this function doesn’t take into account negative numbers, +Infinity, NaN (not a number) values or any number that’s ridiculously high that is close to +Infinity. I’ll revisit tidying this function up later on.

We’ll be taking advantage of this function in a later post where we use this to derive another alternate version of another JavaScript method. More on that later. Next post will be used to focus on the derivation of the three main trigonometric functions in a similar fashion as above.

Before I sign off for today, I wanted to thank a fellow code golfer, Arnauld, for his insight of taking advantage of zero underflow to golf this down; it was much appreciated.

Until the next post!

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…

#BecauseJavaScript Part 3 – Undefined makes a comeback…


Once again, I’m having to explain why JavaScript behaves a certain way… Programmers other than myself are baying for Brendan Eich’s blood because they don’t understand what is happening and just chalk it up to #BecauseJavaScript…

Let’s take a look at an example here:


Here, Vishal Gupta, not content with the result he’s been given by JavaScript has taken to Twitter to complain about it…

Dude, chill, have some guacamole and sit back and let Uncle Eliseo take you on a guided tour on why JavaScript gave you “3” as to the answer to life, the universe and everything… And not “42”.

Let’s take a look at the syntax:

‘Befundefinedit’.indexOf()

Result: 3

So, we have a string ‘Befundefinedit’, being actioned by the indexOf method. The only exception is that there’s no string value being passed as a parameter… You could say that parameter is undefined…

And you would be right, but at the sane time, the parameter is also undefined. Yes, just because no value has been passed through doesn’t mean JavaScript will accept that at face value (no pun intended). JavaScript will consider what type of value is expected and coerce whatever has been passed through, even if the parameter passed is undefined. If it’s undefined, then JavaScript will be all like “Okay, buddy, you wanna go with an undefined value? We’ll try to work with you…” and then default value types and loose typing take over…

So in Vishal’s example, undefined is technically passed through the indexOf method, indexOf expects the parameter to be a string, so loose typing coerces undefined to become ‘undefined’ and uses that as its search term. In the string ‘Befundefinedit’ the search term ‘undefined’ appears at index 3 (remembering that strings, just like all arrays in JavaScript, are zero-based), and so it returns 3 as the final answer…

So, what’s our take away here? If a JavaScript method expects a parameter to be a specific type, a value of any other type that is passed to that method will be coerced to the expected type before execution. I’ll repeat this again, in quotes, because I can’t stress it enough…

If a JavaScript method expects a parameter to be a specific type, a value of any other type that is passed to that method will be coerced to the expected type before execution.

Another take away is that if a parameter is undefined, JavaScript will take you literally and go with undefined.

That being said, let’s go with a few more examples:

‘This is not a null string’.indexOf(null)

This returns 14. You guessed it, null just got coerced to a string and became ‘null’. The rest is pretty straight forward, as ‘null’ appears at index 14 of the string. I have to admit, I did have a little chuckle when I discovered this some time back.

‘1234567890’.indexOf(0)

This returns 9, as 0 after being coerced to ‘0’ is found at index 9 of the string.

x=(1!=0); ‘misconstrued as falsehoods’.indexOf(x)

This is a tricky one… I’ve predefined x with a Boolean value. We can see that I’ve cleverly put both ‘true’ and ‘false’ within the string. Which index will it return, 7 or 16? Keep your answer to yourself for just a little longer while we examine this one…

!= as everyone knows is the inequality operator in JavaScript. So, is 1 not equal to 0? Damn straight, so it’s true, so true is the value assigned to x. As x is passed to the indexOf method, it gets coerced to ‘true’ and the above syntax returns… 7. Hands up all those that got it right…

So what if we change it up a little?

x=(1!=0); ‘misconstrued as falsehoods’.indexOf(!x)

The only difference here is that we’ve passed through x which has also been acted upon by the negation operator, !. As a result, !x is passed, which means false its passed, which is coerced to ‘false’ which results in 16 being returned in this instance.

So, where do we go from here…? Just a reminder that if JavaScript gives you an answer that is perplexing or in Vishal’s case, so detrimental to his well-being that he took to Twitter to bemoan the fact that this syntax was the bane of his existence; take a step back and look at how the syntax you’re using works, what it expects, and how loose typing may have come into play.

I have a doozy of a next post that will make your freaking heads spin coming soon. In the mean time, have a great day!

#BecauseJavaScript Part 2 – String Comparisons

Welcome back!

I delved into Twitter again and found this little tweet by Nico Castro. This is a quick one, but it does need a fair bit of explanation to clarify things.

So what’s going on here? Why is the small ‘a’ greater than capital ‘Z’, but at the same time has capital ‘A’ not greater than capital ‘Z’?

Nico is on the right track, ASCII has a lot to do with it, but it’s a teeny tiny bit more complex than that… Let’s take another look at those two statements:

"a" > "Z" // true

"A" > "Z" // false

So, as I said, there is some focus on the ASCII component of the strings that comes into play.

Let’s replace the strings with their ASCII numeric equivalents. Once we do, we see something that instantly clicks:

97 > 90 // "a" > "Z" == true!

65 > 90 // "A" > "Z" == false!

Ta-dah! JavaScript has this unique way with comparing strings when it comes to the greater-than and lesser-than operators. In comparing strings, JavaScript treats them as arrays comprised of single character elements, so in the first example, JavaScript is really comparing [“a”] against [“Z”], JavaScript then compares both arrays, index by index.

Here are three more examples…

"ab" > "ac" // false
"ab" > "a" // true
"ate" > "are" // true

The first example gets converted to their respective arrays: [“a”,”b”] and [“a”,”c”], and then runs through the conversions to the numeric equivalents: [97,98] and [97, 99]. From there, JavaScript will compare these two arrays index by index until it finds a pair that satisfies the comparison operator in question. If it cannot find a pair of elements satisfying the comparison false is returned, otherwise it will return true. If, however, we find a pair of elements that does satisfy the comparison, it returns true and breaks out of the check. So in this first example, the zeroth element for both arrays is 97. 97 isn’t greater than 97, so it then tests out the first elements of, 98 against 99, 98 is not greater than 99, and thus because we’ve reached the end of both arrays without anything satisfying the comparison, it returns false.

Second example is slightly trickier. We have a two character-long string compared against a single character. What happens there?

If you were to type “a”[0] into a JavaScript console, you’d get returned “a”, the zeroth element in the array. So far, so good. However, were you then to type “a”[1] into the console, you’d get returned undefined, which makes sense because in a single element array there will only the element at index 0, and no other, so any index above zero will return undefined.

So “a” which we know is the same as [“a”] is also technically equivalent to [“a”, undefined]!

In short, when comparing strings with greater-than or lesser-than operators, the shorter string will be “appended” with undefined instances when converted to an array until both arrays are of equal length before doing the final series of comparisons. And because undefined is a falsy value, when compared, the undefined gets coerced to 0.

With all that said and done, we finally end up with: [97,98] (“ab”) and [97,0] (“a”). Comparing the two arrays, We get the zeroth elements not satisfying the > operator, but the first elements do, so true is returned.

Finally, we compare “ate” with “are”. When both strings are converted to numeric arrays for comparison we have [97, 116, 101] and [97, 114, 101] . The rest is a foregone conclusion:

Index 0; is 97 > 97? No, move onto index 1.

Index 0; is 116 > 114? Yes! Ding Ding Ding! Stop processing and return true.

So there you have it, string comparisons with lesser-than and greater-than operators. And yes, it’s a pain in the ass that JavaScript computes comparisons like this, but once you stop and look at the process of how it does it, there’s a greater appreciation of how the language works.