How Does Sort Method Work in JavaScript?

Photo by Charles Deluvio on Unsplash

Basic Understanding of Sort Method

The sort() method, as its name suggests, sorts every element in an array.

default sorting

Customizing Sort Order — CompareFunction

When sorting the array that only has numbers, how do you think the elements would be ordered?

sorted numbers without compareFunction
sorted numbers with compareFunction
sorted number in descending order
sorted strings in descending order
["lettuce", "cabbege", "tomato", "cucumber", "onion", "squash"]
["lettuce", "tomato", "cabbege", "cucumber", "onion", "squash"]
["tomato", "lettuce", "cabbege", "cucumber", "onion", "squash"]
sorted in chronological order

Heads-up!

Last but not least, this method acts on the existing array unlike map() or filter().

Keeping the original array

Japanese women who code at home.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store