“Conjuring” the Demons of the .sort() Javascript Method

Lorraine Warren (Vera Farmiga) absolutely terrified of .sort()!

The .sort Javascript method is scary, right? It definitely terrified me when I tried to use it during a React coding challenge during my software engineering bootcamp at Flatiron School, NYC. Why was it so difficult to grasp? What parameters does it accept? Will localeCompare.() conjure the nun from The Conjuring 2 (and its subsequent spinoff, 2018’s “The Nun”)?!?!

I’m going to attempt to demystify some of these questions, and possibly more, in the following paragraphs. WARNING: not for the faint of programming-heart.

In 2013’s “The Conjuring” and 2016’s “The Conjuring 2”, Vera Farmiga and Patrick Wilson play Lorraine and Ed Warren, two very well-known and real-life paranormal investigators. In the Conjuring universe, Ed and Lorraine have successfully expelled demons and helped numerous families find peace with the paranormal activity that had plagued them. They find themselves overwhelmed, however, finding a way to sort through the numerous demons that they’ve crossed paths with over the years!

Luckily for them, they’ve found just the right Javascript method that will allow them to sort through their extensive list of admonished demons — .sort()! Unluckily though, it’s so confusing with their novice programming skills! Not to fear — we can help them by explaining some common missteps and pitfalls with .sort().

Let’s say Ed and Lorraine have created a list (array) of names of some of the demons they’ve exercised over the years:

Ed’s ADD is getting the best of him and he absolutely HAS to have his demon list in alphabetical order (Lorraine: 😒). Luckily, .sort() can help him.

According to the MDN Docs, “The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.” So, what this means, is that .sort() mutates(changes) the original array, which Ed is completely OK with.

.sort() accepts up to three parameters:

  1. a “compareFunction”(which is optional) and:

2. and 3., two elements for comparison. Since the “compareFunction” is optional, let’s see how we can use .sort() with and without it.

By simply calling demons.sort(), Javascript performs some “under the hood” magic to mutate the array of names of Ed’s demons and return them sorted alphabetically, in place.

What is that magic, you ask? Well, our earlier .sort definition says “… The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.” UTF-16 means Unicode value. In layman’s terms, Unicode values for strings are actually numbers. .Sort then takes these unicode values and sorts them sequentially by default. Luckily for Ed, his demons’ names are already strings, so no conversion needed. Also, calling .sort() here without a compare function only works because all of the demons’ names are similar in case. If Ed had typed one, or some, in with lowercase first letters, he would have received errors. That would be a case for .localeCompare(), which can compare strings no matter the case used.

Ed Warren (Patrick Wilson) strumming a happy tune after sorting his demons!

Ed stumbles across another problem in his record keeping, however. He has a new list of demon objects(key: value pairs), including their birth and death years. The Church has now asked Ed for this list to be returned sorting the demons by their age, not alphabetically. Fortunately for Ed, .sort will allow him to do just that and appease the Priests that he works so closely with during exorcisms.

For Ed to accomplish this task, he’ll now have to incorporate a “compareFunction” to his .sort method. Again, according to the MDN docs, “… If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function.”

Ok, so. The return value of the compare function. As .sort runs its comparison loop, values will be returned one of three ways; -1, 0, or 1.

  • If the return value is -1, A will be displayed before B.
  • If the return value is 0, the order of the values will remain unchanged as when the loop began (meaning they’re the same values).
  • If the return value is 1, B will then be displayed before A.

Here, by using an arrow comparison function, Ed is comparing each demon to the next based on the value of their death year subtracted from their birth year. Based on their return values, if Ed calls console.table(oldestDemons), he’ll receive a nicely formatted table of his demons sorted from oldest to youngest, as shown below:

But wait, the Church has changed its mind and would like that same list now sorted alphabetically. Just for fun, Ed decides to use .localeCompare() just to stretch his newfound understanding of sorting using Javascript’s compare functions within .sort():

Look at that, his nicely formatted table now displays all of his demonic information now sorted by name instead of age, based on their 1, 0, -1 return values when compared against one another.

Thrilled the terrifying sorting is over.

When first learning about .sort() and it’s associated “compareFunction”-ality, I once again got hung up on understanding why it functions the way it does. I wrote about this in a previous blog; being hung up on the “why” instead of just realizing that it works, and I don’t need to understand why. I guess this comes back to SE’s being “lazy;” just use it because it works to get the job done!

Since the “compareFunction” is optional, let’s see how we can use .sort with and without it.

Recent Flatiron School Grad, hopeful SE in search of a job!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store