Why we here contract a and b?

this code sort numbers within an array. but why do we need to contract a and b at the end?

function getIndexToIns(arr, num) {
  arr.sort(function(a, b) {
    return a - b;


The .sort() function has some odd behaviours. For our example, let’s use this array:

const array = [1, 8, 43, 12, 27, 9, 3, 31]

Okay - now if we just call array.sort() and use the default sorting method, it converts the numbers to strings and then sorts in ascending value. This results in:

[ 1, 12, 27, 3, 31, 43, 8, 9 ]

This is not correct! 3 is a much smaller number than 27, but it comes after in this method because 3 comes after 2. When these are converted to strings, it’s similar to sorting alphabetically.

So instead we need to use a callback function to tell the .sort() how we want things sorted. That callback function should take two parameters a and b. a and b will be two elements in the array, and sort will iterate through all of the elements. The function should return a number. If that number is less than 0, sort will say "a should come before b." If that number is greater than 0, sort will say "b should come before a". If that number is 0, sort will say “These are the same, leave them alone”.

Now we can look at your function:

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

The function you’ve provided will check a-b. If a is the larger element, this value will be greater than 0 (which means sort will put b before a). If b is the larger element, this value will be less than 0 (which means sort will put a before b). We can try this with our example array above, and we get:

[ 1, 3, 8, 9, 12, 27, 31, 43 ]

This works because now we are checking the actual values of the numbers, rather than converting them to strings.

I hope this helps clear things up a bit! :slight_smile:


I didn’t know sort will convert items of an array into strings! I am glad I asked about it.
Thank you so much for the comprehensive explanation. I appreciate it. :slight_smile:

I am glad I was able to help! I apologise if I got a little long-winded there :sweat_smile:

1 Like

Because you may encounter this sort of thing in other places, the default sorting behavior is called a “lexical sort” which is the computer version of sorting alphabetically. BUT even if you want to sort alphabetically, you probably want “A” and “a” to be treated the same (or maybe as neighbors). That isn’t the default behavior, so you need to address that either by sorting case-controlled strings or modifying your sort function.

Programming isn’t hard because computers are smart. It’s hard because computers are very very stupid.


:smile: yes, very accurate. thank you