**sort()** mutates the original array and returns it. The default sort converts elements to strings and sorts by UTF-16 code units — this gives wrong results for numbers (`[10, 9, 2].sort()` → `[10, 2, 9]`). Always provide a **comparator function** `(a, b) => a - b` for numbers. The sort is stable in modern JS engines.
1Understanding Array.sort()
sort() mutates the original array and returns it. The default sort converts elements to strings and sorts by UTF-16 code units — this gives wrong results for numbers ([10, 9, 2].sort() → [10, 2, 9]). Always provide a comparator function (a, b) => a - b for numbers. The sort is stable in modern JS engines.
sort() MUTATES the original array. Use [...arr].sort() to sort a copy if you need to preserve the original.
// WRONG: default sort on numbers
const nums = [10, 9, 2, 1, 11];
console.log([...nums].sort()); // [1, 10, 11, 2, 9] WRONG!
// CORRECT: numeric comparator
console.log([...nums].sort((a, b) => a - b)); // [1, 2, 9, 10, 11]2Practical Example
Here is a real-world application of Array.sort() showing how it is used in production JavaScript code.
// Sort objects by property
const people = [
{ name: 'Charlie', age: 35 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
];
people.sort((a, b) => a.age - b.age);
console.log(people.map(p => p.name)); // ['Alice','Bob','Charlie']3Best Practices
Follow these guidelines when working with Array.sort():
1. Always provide a comparator for numeric sorting
2. Use [...arr].sort() to avoid mutating the original
3. For stable sort of objects, include all sort keys in the comparator
Tip: sort() MUTATES the original array. Use [...arr].sort() to sort a copy if you need to preserve the original.
// WRONG: default sort on numbers
const nums = [10, 9, 2, 1, 11];
console.log([...nums].sort()); // [1, 10, 11, 2, 9] WRONG!
// CORRECT: numeric comparator
console.log([...nums].sort((a, b) => a - b)); // [1, 2, 9, 10, 11]