I don't understand how the JavaScript sort() method works!

I was completing the “Sort an Array Alphabetically using the sort Method” challenge but i don’t get it at all.
I need help please.

First of all, do you understand what it does? It sorts.

const arr = ['butterfly', 'cat', 'apple']

arr.sort()

console.log(arr)
// ['apple', 'butterfly', 'cat']

The default is to just sort alphabetically, like a dictionary.

Are you asking how it works? JavaScript provides a built in method (function) that is built into all arrays. If you call it, it will sort that array.

Are you asking how it does it on a low level? That would be getting into sort algorithms. For now just know that the sort method sorts things.

I don’t know if you’re there yet, but if you want something besides alphabetic sorting, we can send a callback to tell sort how to compare elements. Judging by your wording, I’m guessing that you aren’t there yet.

If that doesn’t answer your question, please be very specific - include code samples if you need to.

1 Like

Thanks a lot for your precious help I finally understand it.