Array.prototype.sort has several traps: it sorts elements as strings by default, mutates the original array, and requires a correct comparator function for numeric or custom sorting. These pitfalls cause many subtle bugs in real-world code and interviews. Sorting is in-place and lexicographic by default; test numeric comparisons and stability for performance.
Array.sort Pitfalls in JavaScript (Lexicographic Sorting, Mutation, Comparator)
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The big trap
Array.prototype.sort() sorts elements as strings by default. That means numbers are compared lexicographically, not numerically.
const nums = [1, 2, 10, 21];
nums.sort();
console.log(nums); // [1, 10, 2, 21] ❗ (string comparison)
The correct numeric sort
const nums = [1, 2, 10, 21];
nums.sort((a, b) => a - b);
console.log(nums); // [1, 2, 10, 21] ✅
Pitfall #1: It mutates the original array
sort() sorts in place. If you’re in React/Angular/Redux and expect immutability, this can silently corrupt your state.
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log(original); // [1, 2, 3] ❗ mutated
console.log(sorted === original); // true
Safe pattern:
const original = [3, 1, 2];
const sorted = [...original].sort((a, b) => a - b);
console.log(original); // [3, 1, 2] ✅
console.log(sorted); // [1, 2, 3]
Pitfall #2: Wrong comparator logic
The comparator must return:
- < 0 if
ashould come beforeb - > 0 if
ashould come afterb - 0 if equal
Returning true/false is a bug.
// ❌ Buggy comparator
arr.sort((a, b) => a > b);
// ✅ Correct
arr.sort((a, b) => a - b);
Pitfall #3: Sorting objects
You must compare a specific field:
const users = [
{ name: 'Bob', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Carol', age: 35 }
];
// By age
users.sort((a, b) => a.age - b.age);
// By name (locale-safe)
users.sort((a, b) => a.name.localeCompare(b.name));
Stability note
Modern JavaScript engines (ES2019+) guarantee that sort is stable, but older engines did not. In interviews, it’s good to mention that today it is stable by spec.
One-sentence answer
Array.sort() sorts in place and compares items as strings by default, so you must clone the array for immutability and provide a correct numeric or custom comparator to avoid subtle bugs.
Practical scenario
Sort prices or dates before rendering a table; a numeric comparator is required to avoid lexicographic order.
Common pitfalls
- Forgetting
sortmutates the original array. - Using an inconsistent comparator that breaks ordering.
- Assuming default sort is numeric.
Copy before sorting to keep immutability. Test with negative numbers and verify stability for performance-sensitive lists.