You’re being irrational… No, wait… That’s π and e…

So, in my last post I said I was going to tackle pushing the limits of JavaScript and create non-native functions that can derive the values of two irrational numbers: π and e. I also said I was going to use similar methods to derive these values. I plan to follow through on this promise…

So let’s take a look at what I reckon would be the harder of the two: the derivation of π.

π – the number… not the tasty baked good.

So, when it came to doing this, I did a little research into the various formulae that have been used to calculate π. I came across this little tidbit from Madhava of Sangamagrama:

This is an infinite series that rapidly converges to the value of π, and Madhava was from the 14th century… And using the square root of 12… Who would have thought of this back then..?

If you recall from two posts ago I had created a square root function, so this part is easy… I’ve also dealt with cumulative sums before in my previous post with the derivations of the non-native sine and cosine functions, and I’ve also created an integer power function as well. So technically, we have all the ingredients to make some delicious “π” (pun intended)…

So let’s take a look at building this up. Let’s grab the two main functions we need to make this happen, the square root function and the power functions:



These two functions were discussed in previous posts. The integer power function p(x,y) raises a positive integer, x, to the power of another positive integer, y. Whereas the square root function r(x), takes a number, x, and runs Newton’s Method of Approximation for square roots until zero underflow is reached in order to provide the square root.

Using these two functions we’ll put together a pi() function that uses these two and one other function (the cumulative sum function) that we’ll create right now:


Those who have followed my blog well enough will have recognized that this is a recursive function. This loops through from k down to zero and with each iteration added the equivalent of (-3-k)/(2k+1). Because the integer power function works only with positive powers of y, a simple reciprocal equates to the negative power of y. As this P() function converges quite quickly, you only need 100 iterations before JavaScript’s zero underflow kicks in, P(99), which will give us 100 iterations (0-99) should give us that without breaking a sweat. After that it’s simply a case of multiplying the result with the square root of 12:


The results will surprise you:

pi() gives 3.141592653589794

Math.PI gives 3.141592653589793

Which is more accurate? According to WolframAlpha, the sequence after the 97 goes 93238… And while JavaScript’s native value wins this round, you have to admit, that’s pretty reasonable accuracy just using recursive functions and standard operators… Now let’s turn out focus to the other guy…

e – the number… I’ve got nothing to compare this against, so let’s just get on with it…

Okay, this is far simpler… e is defined as the cumulative sum of the reciprocals of all natural integer factorials from zero and above… In other words:

It’s interesting to note that as 0! and 1! are both equal to 1, the first two terms of this series make up about 73.5% of the total value of e… Just thought I’d randomly share that bit of trivia there…

Anyhow… If we create a similar cumulative function called e() which adds the reciprocal of reach natural integer factorial, borrowing our factorial function from my post a few weeks ago:


…we then have our function… 100 iterations would once again be sufficient to get to our value within acceptable accuracy… Put to the test:

e(99) gives 2.7182818284590455

Math.E() gives 2.718281828459045

WolframAlpha shows e as continuing after the 2845 with 904523, so apart from that last digit in the return value from our function, it’s practically identical and with a surprising amount of accuracy!

So there we have it… We’ve succeeded in deriving two irrational numbers using a few fundamental functions through basic operators, recursion and fat arrow functions.

My next post will focus on something we touched a little earlier on – JavaScript obfuscation; in this case a challenge set by a fellow code golfer to test me… Goodness knows why… But we’ll take a look in my next post. Until then, stay quirky!


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!

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.




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, 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:




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:



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.


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:


Which can then be thrust back into our function:


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:


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, but solely in reference to indexing. Strings are not subject to any methods like arrays are, save for indexing… and the length method… Maybe a few more, I’d have to check, but length is definitely one method arrays and strings have in common… 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 but solely in reference to indexing… and the length method.

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


which when we apply all the concatenation operators gives us:


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:


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


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:


You’d be doing the exact same thing as:


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:


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.


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:


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


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:


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…

Here’s another post which explains why JavaScript behaves a certain way…

Regrettably, there are programmers 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, has mentioned his befuddlement re the result he’s been given by JavaScript…

Vishal, I’m happy to take you on a guided tour on why JavaScript gave you “3” as your answer in this case.

Let’s take a look at the syntax:


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.


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; 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 and stay quirky!