๐Ÿš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
๐ŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
JS MASTER CLASS /// MASTER THE ENGINE /// BUILD LOGIC /// ASYNC PATTERNS /// JS MASTER CLASS /// MASTER THE ENGINE ///

Array.prototype.sort() | JavaScript Tutorial - In-Depth Guide

Master Array.prototype.sort(): why the default sort is alphabetical (even for numbers), writing correct comparator functions, its mutation behavior, and stability guarantees.

โšก Total XP: 0|๐Ÿ’ป javascript XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

What does `[10, 1, 2].sort()` (no comparator) return?


๐Ÿš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
๐ŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

sort() is one of the most misused array methods in JavaScript: it mutates the original array in place, and its default comparator converts everything to strings โ€” silently breaking numeric sorts unless you supply your own comparator.

1Array.prototype.sort() | JavaScript Tutorial - In-Depth Guide Part 1

sort() mutates the array in place and also returns it โ€” a rare case among modern array methods of both mutating and returning.

โœ•
โ€”
+
const nums = [3, 1, 2];
const sorted = nums.sort();
sorted === nums; // true โ€” same array, mutated in place
localhost:3000
๐Ÿ”€

Mutates In Place

2Array.prototype.sort() | JavaScript Tutorial - In-Depth Guide Part 2

Without a comparator, sort() converts every element to a string and compares them alphabetically โ€” which breaks numeric ordering.

โœ•
โ€”
+
[10, 1, 2].sort(); // [1, 10, 2] โ€” alphabetical, not numeric!
localhost:3000

The Default Is Alphabetical

3Array.prototype.sort() | JavaScript Tutorial - In-Depth Guide Part 3

A comparator function fixes this: return a negative number if a should come first, positive if b should, or zero if they're equal.

โœ•
โ€”
+
[10, 1, 2].sort((a, b) => a - b); // [1, 2, 10] โ€” correct
localhost:3000

The Comparator Function

4Array.prototype.sort() | JavaScript Tutorial - In-Depth Guide Part 4

Sorting an array of objects by a property requires comparing that specific property inside the comparator.

โœ•
โ€”
+
users.sort((a, b) => a.age - b.age);
names.sort((a, b) => a.localeCompare(b));
localhost:3000

Sorting by Property

5Array.prototype.sort() | JavaScript Tutorial - In-Depth Guide Part 5

Modern JavaScript engines guarantee sort() is stable โ€” elements that compare as equal retain their original relative order.

โœ•
โ€”
+
// Elements with equal keys keep their relative order:
people.sort((a, b) => a.lastName.localeCompare(b.lastName));
localhost:3000

Stable Sort Guarantee

6Step-by-Step Breakdown

sort() mutates the array in place and also returns it โ€” a rare case among modern array methods of both mutating and returning.

Checkpoint: After calling arr.sort(), is the original arr variable's array mutated?

  • โ†’Yes, sort() mutates the array in place
  • โ†’No, it always returns a new array

Without a comparator, sort() converts every element to a string and compares them alphabetically โ€” which breaks numeric ordering.

Checkpoint: What does [10, 1, 2].sort() (no comparator) return?

  • โ†’[1, 10, 2], sorted alphabetically as strings
  • โ†’[1, 2, 10], sorted numerically

A comparator function fixes this: return a negative number if a should come first, positive if b should, or zero if they're equal.

Sorting an array of objects by a property requires comparing that specific property inside the comparator.

Modern JavaScript engines guarantee sort() is stable โ€” elements that compare as equal retain their original relative order.

Next, we'll explore 'Immutable Sorting with toSorted()'.

Level Up ๐Ÿš€

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Announce Sort Order Changes to Assistive Technology

When a user changes a sortable table's sort column or direction, update the corresponding column header's aria-sort attribute (ascending/descending/none) so screen reader users are informed of the current sort state.

SEO Implications

  • 1

    Consistent Sort Order Improves Perceived Content Stability

    Using a stable, well-defined sort for listing pages (like product or article listings) avoids items appearing to reshuffle unpredictably between visits, which can affect user trust signals even though sort order itself is not a direct ranking factor.

Best Practices

Always Provide a Comparator When Sorting Numbers

The default string-based comparison silently produces wrong results for numeric data, so `(a, b) => a - b` (or `b - a` for descending) should be considered mandatory for numeric sorts.

Copy the Array First If the Original Order Must Be Preserved

Since sort() mutates in place, use `[...arr].sort(...)` (or toSorted()) whenever other code still needs the array in its original order.

Frequent Bugs

THE BUG

Sorting an array of numbers without a comparator, silently producing an alphabetically-sorted (and numerically wrong) result.

THE FIX

Always supply an explicit numeric comparator, e.g. `(a, b) => a - b`, whenever sorting numbers.

THE BUG

Calling `.sort()` on an array that's also referenced elsewhere in the app (like shared state), unexpectedly mutating that shared reference and causing bugs in unrelated code.

THE FIX

Copy the array first with spread (`[...arr].sort(...)`) or use the newer, non-mutating toSorted() method when the original order must be preserved for other consumers.

Real-World Examples

Sorting a Product List by Price, Then by Name

An e-commerce listing needed to sort products by ascending price, with same-priced items ordered alphabetically by name using the sort's stability guarantee.

const sorted = [...products]
  .sort((a, b) => a.name.localeCompare(b.name))
  .sort((a, b) => a.price - b.price);
// Stable sort means the name-sort survives as the tiebreaker

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Sorting numbers without a comparator

numbers.sort((a, b) => a - b);

The Solution //

Always pass an explicit numeric comparator function for numeric data.

Lesson Glossary

[01]Comparator Function

A function passed to sort() controlling element order via its return value.

Code Preview
(a, b) => a - b

[02]Stable Sort

A sort algorithm guarantee that equal elements retain their original relative order.

Code Preview
stable since ES2019

[03]In-Place Mutation

Modifying the original array directly, as sort() does, rather than returning a new one.

Code Preview
arr.sort()

[04]localeCompare()

A String method for locale-aware, correct alphabetical comparison.

Code Preview
a.localeCompare(b)

[05]Default Sort Order

sort()'s behavior with no comparator: convert to strings and compare in UTF-16 code unit order.

Code Preview
string comparison

Continue Learning