Using the Array.sort() function

Vanilla JavaScript Syntax

Yosef S Adelman
3 min readMay 10, 2021
Leonardo DiCaprio smirks with a text overlay of the sort() function being misused.
A great Example of a Logical Error in Coding.

Do you feel like you maybe missing the point of the meme that your technical coach posted on a group chat for your online coding boot camp class???

Oh … Well I was close :/

Here’s some info on how this method works. I call it both a method and a function here, but it means the same thing. Hopefully by the end of this read you will smirk just like Leonardo is.

The sort() function can take an argument to dictate how exactly it sorts your array, but it also could not. You will not see a runtime error if you don’t pass in an argument.

If no arguments are passed, the sort() function sorts items in an array as if they were strings. It literally converts each element to a string and then sorts them. In an alphabetical (string) way, 100000 should go before 21, because it's sorting each character, one at a time.

The same thing happens when the strings 'ale', and 'abnormal' are compared:

Even thought 'ale' has just 3 letters while 'abnormal' has 8, 'abnormal' will obviously go first because sort() is not evaluating the length of each string or what they amount to. It simply knows that B comes before L, and sorts it accordingly.

If we read 21 and 100000 as strings, I think we would all agree that 21 should go after 100000, because 1 comes before 2, and that's it. We aren't bothered that 100000 is more than 4,500 TIMES (I checked) the value of 21, because we just aren't comparing the two by their values.

With that knowledge, we can move to Leonardo’s side of the joke. It kind of seems a bit mean at this point. It’s not such a stretch to think that the sort() function would sort numbers as numbers. It happens to be that it doesn’t, and the return value in the meme actually makes sense. Welcome to JavaScript.

So how do we sort numbers?

Here is where we would be passing an argument to the sort() function. The argument that sort() takes is a callback function, which needs to return a positive or negative value. The positive and negative value is what sort() uses to actually sort items in an array.

Sort() will pass two things to your callback function: one item from your array, and another one from your array. Sort() will run the body of the callback function for every item in your array, comparing it to all the others. In order to use these arguments, we need to assign references to them. For this example, lets call them item1 and item2. Now that we have them, we need a positive or negative value, which we can get by doing basic arithmetic: item1 — item1.

The final, working line of code that would solve our issue, would be: Array.sort((item1, item2) => item1 — item2)

References:

--

--

Yosef S Adelman

Hey, I’m a software engineering graduate from Flatiron School.