# Can someone explain this sort function from w3 tutorial to me

## Recommended Posts

Hi, I needed to sort some numbers using javascript, so I used the tutorial from W3, but I have no idea why this function works. Here's the code:

`<html><body><script type="text/javascript">function sortNumber(a, {return a - b}var arr = new Array(6)arr = "10"arr = "5"arr = "40"arr = "25"arr = "1000"arr = "1"document.write(arr + "<br />")document.write(arr.sort(sortNumber))</script></body></html>`

I'm confused by the function, how does a-b end up making the numbers sort properly?Thanks for your help!

##### Share on other sites

If a is less then b then the return value is negative, and it means that a comes before b. If a is greater then b then the return value is positive, and b needs to come before a. The reverse if you're sorting from high to low. If a and b are equal then the function returns 0 and it won't change the order of the two items being compared. The sort function runs through the array and for each pair of values it comes to, it passes them to the compare function as a and b. The sort function will swap the two elements if the return value is negative, sort backwards until the return value is positive or 0, and then move on to check the next pair. If you want it to sort from high to low then you can have the function return b - a.Also, you shouldn't put those numbers in quotes, it makes them strings.

##### Share on other sites

Thanks, I think I got it now. And thanks for pointing out about the numbers in quotes, but that code was just one I copied and pasted out of the tutorial, it wasn't the actual code I was using. Maybe they should change that.