In JavaScript, you can sort an array using the sort() method. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units' values, as stated on MDN.

This means if you want to sort an array of numbers in ascending order, you can't just use the default sort order. It will give you an unexpected result:

const numbers = [80, 1000, 9];

numbers.sort(); // [1000, 80, 9]

Instead, you need to supply a callback function. If a is less than b, the function should return a negative number. If a is greater than b, the function should return a positive number. If a is equal to b, the function should return zero:

numbers.sort(function (a, b) {
// If a is less than b
if (a < b) {
return -1;
}

// If a is greater than b
if (a > b) {
return 1;
}

// If a is equal to b
return 0;
});

// Result: [9, 80, 1000]

You can shorten this by simply subtracting b from a:

// Traditional function expression
numbers.sort(function (a, b) {
return a - b;
});

// Or...

// Arrow function expression
numbers.sort((a, b) => a - b);

// Either way, the result is still [9, 80, 1000]

This makes sense when you think about it:

  • If a === 1 and b === 2, then (a - b) === (1 - 2) === -1.
  • If a === 2 and b === 1, then (a - b) === (2 - 1) === 1.
  • If a === 1 and b === 1, then (a - b) === (1 - 1) === 0.

It's the same as writing the function in the long form.


If you have any questions, please email me at kieranbarker@outlook.com!