Course contentsShow
← JavaScript
Lesson 903 of 2,72320. Array Iteration and TransformationFree lesson

Stable vs Unstable Sorts

Learn that modern JavaScript guarantees stable sorting, preserving the relative order of equal elements.

Stable vs Unstable Sorts

You'll learn how JavaScript's sort() method preserves the original order of elements that compare as equal—a property called "stability."

What Is Sort Stability?

A stable sort maintains the relative order of elements that are considered equal by the comparator function. An unstable sort might rearrange equal elements unpredictably.

Imagine sorting students by test score. If two students both scored 85, a stable sort keeps them in their original order (say, alphabetical by name). An unstable sort might flip them around arbitrarily.

Why This Matters

Modern JavaScript guarantees stable sorting (as of ES2019). This is crucial when you perform multi-level sorting or when the original order carries meaning.

Consider this example:

const students = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 90 },
  { name: 'Charlie', score: 85 }
];

// First sort by name (already in alphabetical order)
// Then sort by score
students.sort((a, b) => a.score - b.score);

// Alice and Charlie both have 85
// Stable sort guarantees Alice comes before Charlie
// because that was their original order
console.log(students);
// [{ name: 'Alice', score: 85 }, { name: 'Charlie', score: 85 }, { name: 'Bob', score: 90 }]

Without stability, Alice and Charlie might swap positions unpredictably each time you sort, even though they're "equal" according to the score comparison.

Before ES2019

Older JavaScript engines didn't guarantee stability. This meant sorting equal elements could produce inconsistent results across different browsers or runtimes. Now you can rely on consistent, predictable behavior.

Key Takeaway: JavaScript's sort() method is stable, meaning equal elements maintain their original relative order—critical for multi-level sorting and predictable results.