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 JavaScript Foundations Arrays Methods: Part 2

Presley Cobb
Presley Cobb
9,214 Points

Methods Part 2

Im trying to understand the sort method here. Let me start off by explaining what I do understand so you can see what im missing. I understand line and and 2 but what is confusing to me is how javascript is making a and b represent the values in the array. The other confusing part of this is after you figure out if the value is negative or positive how does that value get put back into the array. I have an idea but Im not sure so tell me if im wrong. Does the function use a and b to represent 10 and 44 then determines it has a negative value so it places a 10 before 44? Then is the next step to take 44 and 32 and do the same thing? That would place 10 first then 32 then 44. It seems the disconnect on this question is figuring out how a and b represent the values in the array and then how those values are placed back in the array. Since both of those actions at least to me seem like they would require more code.

var my_array = [10, 44, 32, 100, 0, 44, 3, 4];
console.log(my_array.toString());

my_array.sort(function (a,b) {
  return a - b;
});
console.log(my_array.toString());

2 Answers

The idea is that .sort() keeps grabbing pairs of elements from the array and calls the compare function with those pairs as parameters. If the return value is negative, then the first parameter comes before the second parameter. If the value is 0, then they are the same. If the value is positive, then the first parameter comes after the second parameter.

The actual sorting mechanism is hidden (and can vary between different implementations), and we influence it by defining the compare function.

You can read about it in more detail on MDN.

Presley Cobb
Presley Cobb
9,214 Points

Thank you very much. How this works behind the scenes isn't explained very well. The part I was missing is that the sort function compares two values by default. Thanks for the link.