sort callback function

Understanding the Sort Callback Function

If you are a developer working with arrays, you must have come across the sort method. The sort method arranges the elements of an array in alphabetical or numerical order. However, it might not work as expected in some cases. That's where the sort callback function comes into play.

The Basics of Sort Callback Function

The sort callback function is a function that is passed to the sort method as an argument. It is used to compare two elements of an array and determine their order. The sort method then uses this function to sort the entire array based on the comparison result.

The callback function should return a negative, zero, or positive number, depending on whether the first argument should be before, equal to, or after the second argument, respectively.

Example of Sort Callback Function

let numbers = [4, 2, 6, 1, 3];

numbers.sort(function(a, b) {
  return a - b;

console.log(numbers); // [1, 2, 3, 4, 6]

In this example, we have an array of numbers that we want to sort in ascending order. The callback function takes two arguments a and b and returns the result of subtracting b from a. The sort method uses this result to determine the order of the elements in the array.

Multiple Ways to Write Sort Callback Function

There are many ways to write a sort callback function. Here are some examples:

  • Ascending order: function(a, b) { return a - b; }
  • Descending order: function(a, b) { return b - a; }
  • Sorting an array of objects by a property: function(a, b) { return -; }
  • Sorting strings in alphabetical order: function(a, b) { return a.localeCompare(b); }

It's essential to remember that the sort method modifies the original array. If you want to create a sorted copy of the array without modifying the original, you should use the slice method to create a copy and then sort the copy.


The sort callback function is a powerful tool that allows you to sort arrays in a custom way. By understanding how this function works, you can create complex sorting algorithms that meet your specific needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]