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

geoffrey
geoffrey
28,736 Points

sort() method and its function to sort numerically

Hello, there is something I don't get correctly. To sort an array numerically, we need to use sort( ) with a function such as this.

var myTab = [10,58,1,25,12];

myTab.sort(function(a,b){

return a-b

});

I can remember it, that's not the problem, but that's about the way It really works.

I don't get how javascript and the sort() method know how to compare numbers inside the array, just by giving two paramaters which are anonymous.

Is it something built in the sort() method ?

Because honestly, without knowing that kind of function exists, I would on my side do the comparison 'manually', using a loop to compare each value inside the array to each other.

2 Answers

It may be useful to look at the method definition and explanation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort