Course contentsShow
← JavaScript
Lesson 898 of 2,72320. Array Iteration and TransformationFree lesson

Writing a Numeric Comparator

Create a comparator function that returns negative, zero, or positive to sort numbers in ascending order.

Writing a Numeric Comparator

You'll learn how to create a comparator function that tells sort() exactly how to arrange numbers in ascending order.

The Problem We're Solving

As you saw in the previous lesson, sort() converts everything to strings by default, which makes numbers sort incorrectly (like "10" coming before "2"). A comparator function is your solution: it's a custom function you pass to sort() that compares two elements and tells sort() which should come first.

How Comparators Work

A comparator receives two parameters (often called a and b) and must return:

  • A negative number if a should come before b
  • Zero if they're equal (order doesn't matter)
  • A positive number if a should come after b

Think of it like a judge deciding between two contestants: thumbs down means the first wins, thumbs sideways means tie, thumbs up means the second wins.

Writing a Numeric Comparator

Here's the classic numeric comparator for ascending order:

const numbers = [10, 2, 35, 7];

numbers.sort((a, b) => a - b);

console.log(numbers); // [2, 7, 10, 35]

Why does a - b work perfectly?

  • If a is smaller than b, subtraction gives a negative number → a comes first
  • If they're equal, subtraction gives zero → order stays the same
  • If a is larger than b, subtraction gives a positive number → b comes first

For descending order, just flip it: b - a.

Key Takeaway: A numeric comparator returns a - b for ascending order, using subtraction's natural negative/zero/positive results to guide the sort algorithm.