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

JavaScript Array Sort

Getting an error when I use sort function that return array length of list the words in the array by length order with the shortest first.

        return saying2.length

4 Answers

Try this

saying2.sort(function (a, b) { 
    return a.length - b.length;
Dave McFarland
Dave McFarland
Treehouse Teacher

Adam's answer is right. When you use a sorting function, the 2 arguments you pass to it represent 2 items in the array:

myArray.sort(function( a, b) {


a is one array item and b is another array item. To compare their lengths you just need to use the length property of each:

a.length - b.length

Thanks, I didnot realize you use the substraction for stings.

Thanks that is a great explaination

Great explanation! thank you!