How does sorting array numbers works?

Hello everyone, I hope you are feeling well and happy.
I’m starting with JavaScript, and having struggle to understand how the Array.sort() with number works in the background.

I know that is something like function(a, b){return a - b}, but what happens in the background. How return a-b make an array sort?


sort() method sorts strings by default, doesn’t sorts numbers, so we need a sorting function for it. It does an optimized ‘quick sort’ in the background.

function compare(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;

[1,15,3,21].sort(compare) will give you desired result

1 Like
1 Like

Thanks guys, I understand more now.
Have a good weekend.