Suggest an editImprove this articleRefine the answer for “Sorting an array of numbers”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)By default **`sort()`** converts elements to strings and sorts them in lexicographic order, so an array of numbers gets sorted incorrectly. **Key point:** to sort numbers in ascending order, always pass a compare function: `arr.sort((a, b) => a - b)`.Shown above the full answer for quick recall.Answer (EN)Image## Beginner's mistake: ```javascript const numbers = [10, 1, 3, 20]; numbers.sort(); console.log(numbers); // ["1", "10", "20", "3"] - string sorting ``` By default `sort()` converts elements to strings and sorts them **in lexicographic order** (`"10"` comes before `"2"`). --- ## The correct way: with a compare function ```javascript const numbers = [10, 1, 3, 20]; numbers.sort((a, b) => a - b); console.log(numbers); // [1, 3, 10, 20] ``` - The function `(a, b) => a - b` tells JavaScript **how to compare numbers**: - if `a - b` < 0 -> `a` comes first - if `a - b` > 0 -> `b` comes first - if `a - b` = 0 -> the order stays unchanged --- ## Sorting in descending order: ```javascript numbers.sort((a, b) => b - a); console.log(numbers); // [20, 10, 3, 1] ``` --- ## If you don't want to mutate the original array: ```javascript const arr = [5, 2, 9, 1]; const sorted = [...arr].sort((a, b) => a - b); console.log(sorted); // [1, 2, 5, 9] console.log(arr); // [5, 2, 9, 1] (the original is unchanged) ``` --- ## In short: | Task | Code | Result | |---|---|---| | Ascending | `arr.sort((a, b) => a - b)` | `[1, 2, 3, 4]` | | Descending | `arr.sort((a, b) => b - a)` | `[4, 3, 2, 1]` | | Without changing the original array | `[...arr].sort(...)` | a new sorted array | --- > **Summary:** > To sort numbers in ascending order, > **always pass a compare function:** > > ```javascript > arr.sort((a, b) => a - b); > ```For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.