← JavaScript Foundations
11 / 26
Lesson 11 — sort()
Putting arrays in order
sort() changes an array into sorted order. The catch: by default it compares items as text, so [10, 9, 1].sort() gives [1, 10, 9] ("1" < "9" as text). For numbers, pass a compare function: (a, b) => a - b. A negative result puts a first, positive puts b first.
[5, 1, 4].sort((a, b) => a - b); // [1, 4, 5]
[5, 1, 4].sort((a, b) => b - a); // [5, 4, 1]
Why it matters: price lists, leaderboards and dates all need correct numeric sorting.
Want it another way?
Task
Sort n ascending, then sort a copy descending into high, and log both joined with commas.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.