# Understanding Sort Function in JavaScript

> Why the default sort() doesn't work as expected for numbers, and how to use compare functions for ascending, descending, and string sorting.

By Vishwajeet Raj · 2022-02-11 · https://vishwajeet.co/blog/understanding-sort-javascript

---

## Sort Function

- Used to sort **arrays** in JavaScript.
- This method **mutates** the **original array**.
- By **default**, the **order** is **ascending** but we can change the order.
- We can also provide our compare function to implement custom sorting.

## It Gets Tricky

What happens when you sort `[22, 1, 8, 45, 11, 2, 1]` using the default `.sort()`?

You'd expect `[1, 1, 2, 8, 11, 22, 45]`, but you get `[1, 1, 11, 2, 22, 45, 8]`.

### Why did the sort function not work as expected?

The reason is that the sort method converts the elements into strings and then compares the sequences of their UTF-16 code unit values.

So `1` is converted to `"1"`. When we compare two strings like `"1"` and `"22"`, the char code is compared — char code of `1` is 49, whereas char code of `2` is 50. Because 49 &lt; 50, we get `1, 1, 11` before `2, 22`.

This is where the compare function comes to the rescue.

## Compare Function

The compare function takes two arguments. These arguments are taken from pairs of array elements at indices `[0,1]`, `[1,2]`, ... `[arrayLength-2, arrayLength-1]` to compare each pair of elements.

The sorting of elements is based on the return value of the compare function for each comparison.

If the function returns a value:
- `< 0`, then `a` comes before `b`.
- `> 0`, then the position of `a` and `b` is swapped.
- `=== 0`, then there is no change in position.

## Complete Sort Function for Numbers

### Ascending Order

```js
const arr = [22, 1, 8, 45, 11, 2, 1];
arr.sort((a, b) => a - b);
// [1, 1, 2, 8, 11, 22, 45]
```

### Descending Order

```js
const arr = [22, 1, 8, 45, 11, 2, 1];
arr.sort((a, b) => b - a);
// [45, 22, 11, 8, 2, 1, 1]
```

### Sort Function for Strings

There is no need for a compare function when sorting strings. We can use the default sort method to sort strings.

```js
const arr = ["banana", "apple", "cherry"];
arr.sort();
// ["apple", "banana", "cherry"]
```
