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


Jack Hou
Jack Hou
6,975 Points

Methods Part 2 lecture

in this lecture, Jim went over something like my_array.sort(function( a , b ) ) { return a - b; }

in order to sort the array in numeric order. I have no idea what the above is doing, and the function makes no sense to me. Can someone provide a detail explanation on what Jim is doing here and why it helps to sort the array in order?

1 Answer

The anonymous function inside the sort method (in this case, function(a,b) ) takes 2 parameters (a & b). Since you're performing this method on "my_array", it's going to automatically grab 2 values from the array to compare against each other.

The sorting happens at the return (a-b) line. There are 3 possible results to this statement:

  • Less than 0: Sort "a" to be a lower index than "b"
  • Zero: "a" and "b" should be considered equal, and no sorting performed.
  • Greater than 0: Sort "b" to be a lower index than "a".

Quick example: var myarray=[18, 8, 7, 45] myarray.sort(function(a,b){return a - b})

The first time through, the sort function might compare 18 & 8. Since the resulting number of "a-b" (18-8) is a positive number, the return(a-b) statement will send back >0. When the sort function compares 7 & 45, though, it will return a negative number, so the statement will return <0.

Jack Hou
Jack Hou
6,975 Points

are the two numbers grabbed by a and b random?