The sort() method puts an array in order. With strings, it sorts alphabetically:
const names = ["Omar", "Mia", "Sam", "Zoe"];
names.sort();
console.log(names);
It prints
[ 'Mia', 'Omar', 'Sam', 'Zoe' ]
Easy. Now let's sort some numbers:
const numbers = [10, 1, 5, 100, 25];
numbers.sort();
console.log(numbers);
It prints
[ 1, 10, 100, 25, 5 ]
Wait, what? 100 comes before 25? And 5 is last?
By default, sort() converts every item to a string and sorts them alphabetically, even numbers! As text, "100" comes before "25" because "1" comes before "2", the same way "apple" comes before "banana." To sort numbers properly, you need to give sort a little comparison function:
const numbers = [10, 1, 5, 100, 25];
numbers.sort((a, b) => a - b);
console.log(numbers);
numbers.sort((a, b) => b - a);
console.log(numbers);
It prints
[ 1, 5, 10, 25, 100 ] [ 100, 25, 10, 5, 1 ]
(a, b) => a - b sorts from smallest to largest, and (a, b) => b - a sorts from largest to smallest. Just memorize these two for now. We'll explain exactly how they work in Grade 10.
Also note that sort() and reverse() change the original array. If you want to keep the original order safe, sort a copy: [...numbers].sort((a, b) => a - b). (Newer versions of JavaScript also have toSorted() and toReversed(), which return a new array and leave the original alone.)