Understanding how does arr.sort(function) works

Understanding how does arr.sort(function) works
0

#1

Hello!
I am having triouble understanding how does this code works:

arr = [1,3,6,3,2,6,8];
function sub(a,b) {
return a-b
}
arr.sort(sub);
How we can define a function with 2 arguments, use it with no arguments and in return get something strange: sorted array?


#2

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

Source MDN

I strongly suggest that you get familiar with it.

function sub(a,b) {
return a-b
}

Is basically a function that takes two arguments and in this case subtract them. Since sort can take a callback function which you use by just adding the name unless you create an anonymous one to use, then arr.sort(sub); is just using the sub function as the callback and sort will automatically pass the parameters to it. That is how you define a function with two arguments and use it with no arguments to in return get a sorted array.

How that function works will be answered as you learn about the sort function from the link.


#3

Thanks, but I’m afraid it’s still a mystery to me.