JavaScript Array.sort() Method

Posted on October 31st, 2020
Author: Alex Kimeu

JavaScript Array sort() method.

This method sorts the elements of an array in ascending order by default. It converts the elements from the array to strings then compares their sequences of utf-16 code values. For an array of strings, this works perfectly fine. However, to sort an array of numbers, this method will not work as expected because it converts the elements to strings first.

To achieve what you expect, you can provide a compare function as a callback to the sort method. There are 3 possible outcomes in the callback function: 1. < 0 : a comes first 2. 0 : no change 3. > 0 : b comes first If you want to sort in descending order, you can return b - a in the callback function.