Array.sort Pitfalls in JavaScript (Lexicographic Sorting, Mutation, Comparator)

LowIntermediateJavascript
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

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.

Answer

The big trap

Array.prototype.sort() sorts elements as strings by default. That means numbers are compared lexicographically, not numerically.

JAVASCRIPT
const nums = [1, 2, 10, 21];

nums.sort();

console.log(nums); // [1, 10, 2, 21] ❗ (string comparison)
                  

The correct numeric sort

JAVASCRIPT
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.

JAVASCRIPT
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:

JAVASCRIPT
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 a should come before b
  • > 0 if a should come after b
  • 0 if equal

Returning true/false is a bug.

JAVASCRIPT
// ❌ 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:

JAVASCRIPT
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 sort mutates the original array.
      • Using an inconsistent comparator that breaks ordering.
      • Assuming default sort is numeric.
Trade-off or test tip
Copy before sorting to keep immutability. Test with negative numbers and verify stability for performance-sensitive lists.

Similar questions
Guides
27 / 61