# Compare Function

*noun*

say it: **“kum-PAIR FUNK-shun”** **/kəmˈpɛər ˈfʌŋkʃən/**

The function you give sort() or toSorted(). It gets two items and returns a negative number if the first goes first, a positive number if the second does, or 0 to keep their order.

## What is **Compare Function** in JavaScript?

**Compare Function** — The function you hand to `sort()` or `toSorted()` to say which of two items goes first. It returns a negative number if `a` goes first, a positive number if `b` goes first, and 0 to leave them as they are, so `(a, b) => b - a` puts the highest score first.

```javascript
const scores = [100, 9, 45];
console.log(scores.toSorted((a, b) => b - a)); // [ 100, 45, 9 ]
```

## In a sentence

- “My **compare function**, (a, b) => b - a, put the highest scores first.”

Level: Apprentice · [More JavaScript terms at this level](https://www.ask-codey.com/glossary?category=javascript&level=2)

Updated: November 9, 2026

Source: https://www.ask-codey.com/glossary/compare-function
