Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Theory of comparator function for comparing values in an array.

I'm having a bit of trouble understanding how the function in this video works for comparing the values in the array and sorting them. I know when to use it, I would just like to have a deeper understanding of the process. Thanks in advance!

1 Answer

Hi Kyle,

The compare function doesn't have anything to do with the actual sorting process. This is handled by the sort method using a sorting algorithm. The only job of the compare function is to let the sort method know the relative order of the 2 items that were passed into it.

The sort method will go through the array and it will pass 2 elements at a time to the compare function and the compare function will then return a positive, negative, or zero value which lets the sort method know the relative order of those 2 items.

A negative return value indicates that a should be sorted to a lower index than b

A positive value indicates that b should be sorted to a lower index than a

A zero value indicates that a and b should be considered equal and they may or may not remain in their original order with respect to each other but will be sorted with respect to all other different elements.

You can read more about the sort method and compare function on this mdn page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Thanks Jason,

I had a vague idea of this being the case, but you cleared it up perfectly. Thanks again!