Demystifying the Mysteries of sort() in JavaScript

When sort doesn’t sort

Aphinya Dechalert
Modules&Methods

--

Photo by Ali Morshedlou on Unsplash.

JavaScript has a sort() method that you can use on arrays, but the results are almost always weird and don’t return what you initially expect.

For example, if you have the following [9, 8, 12, 1, 33, 21] array, using sort() on it will return [1, 12, 21, 33, 8, 9].

On the surface, this makes no sense, and that’s because JavaScript’s sort() method isn’t exactly what it makes itself out to be. The array returned is hardly sorted at all — or maybe it is, but just not in the way we want it to be.

This is because JavaScript’s sort() method converts each item in the array into strings and constructs the sequence by comparing each array item based on the UTF-16 code values when there is no callback specified.

UTF what?

I know. Welcome to the seemingly weird but highly logical parts of JavaScript.

How UTF-16 Works

JavaScript is not a typed language — as much as many of us want it to be. When sort()is used, it automatically calls the String() cast method on every array element by default and turns everything into a string. It does this in order to ensure that things can be sorted in a uniform manner. It’s easier to sort when things are the…

--

--

Aphinya Dechalert
Modules&Methods

Where Development Meets Storytelling: Tech Writer, Editor & Dev Advocate. Translating Complexity into Clarity. DM me. linkedin.com/in/dechalert