JS array sort gotchas header

Array.prototype.sort() looks harmless. It isn’t. Two quiet behaviors — in-place mutation and lexicographic default ordering — cause some of the most common silent data-corruption bugs in JavaScript. Here’s what actually happens and how to stay safe.

The Surprise: sort() Mutates in Place

sort() does not return a new array. It reorders the array in place and hands back a reference to the same array. Every other variable pointing at that array now sees the sorted data — even ones you thought were read-only.

const data = [{ name: "banana" }, { name: "apple" }, { name: "cherry" }];
const original = data; // another reference to the same array

const sorted = data.sort((a, b) => a.name.localeCompare(b.name));

console.log(data === sorted);   // true — it's the SAME array object
console.log(original[0].name);  // "apple" — original was mutated too!

The Second Surprise: Default Sort Is Lexicographic

Call sort() with no comparator and every element is coerced to a string and compared by UTF-16 code-unit order. Numbers do not sort numerically:

const numbers = [10, 2, 33, 4, 1];
numbers.sort();
console.log(numbers); // [1, 10, 2, 33, 4] — "10" < "2" lexicographically!

This silently produces wrong orderings in tables, dashboards, and charts — and it usually ships to production because the bug isn’t loud.

The Fix

Always pass an explicit comparator, and protect the source array by sorting a copy.

// Numbers — always provide a comparator
const numbers = [10, 2, 33, 4, 1];
const asc = [...numbers].sort((a, b) => a - b); // [1, 2, 4, 10, 33]

// Never mutate the original: spread (or .slice()) before sorting
const data = [{ score: 3 }, { score: 1 }, { score: 2 }];
const ranked = [...data].sort((a, b) => a.score - b.score);
console.log(data.map(d => d.score)); // [3, 1, 2] — untouched

Quick Reference

  • arr.sort(cmp) mutates arr and returns it — the return value is not a copy.
  • No comparator ⇒ values become strings ⇒ numbers sort wrong.
  • Defensive pattern: [...arr].sort(cmp) or arr.slice().sort(cmp) to protect the source.
  • For locale-aware string sorting, use localeCompare, never the default order.

Why It Matters

Together these two behaviors cause subtle, hard-to-reproduce bugs: a “read-only” view silently reordering a shared store, or a report that prints [1, 10, 2, 33, 4]. Reaching for sort() without a comparator or a copy is one of the most common silent data-corruption mistakes in JS — and now you know how to avoid it.