Misbehaving sort

The default behaviour of Array.prototype.sort() in Javascript may not be what you expect if no compare function is provided.

Photo by Faris Mohammed on Unsplash

I needed to sort an array of integers in Javascript in ascending order recently and reached for Array.prototype.sort().

I have used this function many times over and have never encountered any problem. I am aware that you can pass in a compare function as an optional parameter to customise the sorting behaviour, i.e. array.sort([compareFunction]). But for plain old sorting integers ascendingly, the assumption was it was an overkill.

How wrong I was 🤦‍♂! The value of array after being sorted was:

Time to reach for the official documentation:

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

So it turns out that without an explicit compare function, Javascript would treat all array elements as strings! The fact that the array only contains data of type number is by the by. It actually makes sense as Javascript is a dynamic language. It does not ask you to declare the data type for the array upon declaration so it would not know your intention. Each item in an array can be of any data type, so Javascript needs to work at the lowest common denominator level.

Once it’s clear, the fix was very simple indeed. Here is how to sort an array of numbers ascendingly in Javascript properly:

Have you been tripped by this behaviour before?

Software developer

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