JavaScript Array sort() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
In-place reorder

What You’ll Learn

The sort() method reorders array elements in place. By default it sorts as strings—which surprises beginners with numbers. This tutorial covers compare functions, ascending/descending order, sorting objects, and safe copy-first patterns.

01

Syntax

sort(compareFn?)

02

Default

String order

03

Numbers

(a,b)=>a-b

04

Mutates

Same array

05

Objects

By property

06

ES5+

Universal

Introduction

Need names A–Z, prices low-to-high, or scores on a leaderboard? sort() rearranges elements inside the array. It returns the same array reference (now reordered), so you can chain or assign in one expression.

The catch: without a compare function, JavaScript converts each value to a string before comparing. That works for words but often breaks for multi-digit numbers.

Understanding the sort() Method

array.sort(compareFn?) sorts elements in place using UTF-16 string order when no function is provided. With a compare function, you control ordering: return negative if a comes first, zero if equal, positive if b comes first.

Modern JavaScript requires a stable sort: equal elements keep their relative order from before the sort.

💡
Beginner Tip

For numbers, memorize one line: (a, b) => a - b for ascending. Flip to b - a for descending. For strings, use localeCompare: (a, b) => a.localeCompare(b).

📝 Syntax

General form of Array.prototype.sort:

JavaScript
array.sort(compareFn(a, b))

Parameters

  • compareFn (optional) — defines sort order. Omitted = string sort.

Return value

  • The sorted array (same reference as the original).

Compare function return values

  • < 0a before b
  • 0 — leave order unchanged (stable tie)
  • > 0a after b

Common patterns

  • arr.sort() — default string order.
  • arr.sort((a, b) => a - b) — numbers ascending.
  • arr.sort((a, b) => b - a) — numbers descending.
  • [...arr].sort(fn) — sort a copy, keep original.
  • items.sort((a, b) => a.price - b.price) — objects by field.

⚡ Quick Reference

GoalCode
String A–Zarr.sort() or localeCompare
Numbers ascendingarr.sort((a,b)=>a-b)
Numbers descendingarr.sort((a,b)=>b-a)
Keep original order[...arr].sort(fn)
Non-mutating (modern)arr.toSorted(fn)
Mutates array?Yes

📋 sort() vs reverse() vs toSorted() vs slice()

Sort by rules; reverse flips order; copy patterns preserve originals.

sort
by compare

Mutates

reverse
flip ends

Mutates

toSorted
new array

ES2023

slice + sort
copy first

Classic

Examples Gallery

Open DevTools Console (F12) or use Try-it labs. Example N maps to ?tryit=N.

📚 Getting Started

Default string sorting and the classic number pitfall.

Example 1 — Sort Strings Alphabetically (Default)

Default sort() works well for plain strings.

JavaScript
const fruits = ["banana", "apple", "cherry"];

fruits.sort();

console.log(fruits);
// ["apple", "banana", "cherry"]
Try It Yourself

How It Works

Each element is compared as a string by UTF-16 code units. apple comes before banana.

Example 2 — Default Sort Pitfall With Numbers

Without a compare function, numbers sort like strings—often wrong.

JavaScript
const nums = [40, 5, 100, 9];

nums.sort();

console.log(nums);
// [100, 40, 5, 9]  ← not numeric order!
Try It Yourself

How It Works

Compared as strings: "100" < "40" because "1" < "4". Always use a compare function for numeric sorting.

📈 Practical Patterns

Compare functions, descending order, and object arrays.

Example 3 — Sort Numbers Ascending

Use subtraction in the compare function.

JavaScript
const nums = [40, 5, 100, 9];

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

console.log(nums);
// [5, 9, 40, 100]
Try It Yourself

How It Works

When a < b, a - b is negative, so a is placed first. True numeric ascending order.

Example 4 — Sort Numbers Descending

Flip the subtraction for high-to-low order.

JavaScript
const scores = [88, 42, 95, 71];

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

console.log(scores);
// [95, 88, 71, 42]
Try It Yourself

How It Works

b - a reverses the comparison. Largest values move to the front.

Example 5 — Sort Objects by a Property

Sort products by price ascending.

JavaScript
const products = [
  { name: "Laptop", price: 1200 },
  { name: "Tablet", price: 500 },
  { name: "Phone", price: 800 }
];

products.sort((a, b) => a.price - b.price);

console.log(products.map((p) => p.name + ": $" + p.price).join(", "));
// Tablet: $500, Phone: $800, Laptop: $1200
Try It Yourself

How It Works

Compare a field on each object. Same numeric pattern: a.price - b.price. For strings, use a.name.localeCompare(b.name).

🚀 Common Use Cases

  • Leaderboards — scores high-to-low.
  • Product lists — sort by price or rating.
  • Names — alphabetical user directories.
  • Dates — compare timestamps or Date objects.
  • Table UI — column header click sorting.
  • Immutable display[...data].sort(fn) for React state.

🧠 How sort() Runs

1

Receive compare fn

None? Use string conversion order.

Setup
2

Compare pairs

Engine picks a sort algorithm (stable in modern JS).

Compare
3

Reorder in place

Elements move inside the same array.

Mutate
4

Return array

Same reference, now sorted.

📝 Notes

  • Mutates the original array.
  • Default sort = string UTF-16 order, not numeric.
  • Returns the sorted array (same reference).
  • Stable sort since ES2019 (equal items keep relative order).
  • For immutability: [...arr].sort(fn) or toSorted(fn).
  • Undefined and holes behave per spec—avoid sparse arrays when sorting.
  • Do not assume a specific algorithm (TimSort-like internally in V8).

Browser & Runtime Support

Array.prototype.sort() is one of the oldest array methods—available since JavaScript 1.2. All browsers support it. Modern engines implement a stable sort (ES2019).

Baseline · Universal

Array.prototype.sort()

Supported everywhere: Chrome, Firefox, Safari, Edge, IE, and all Node.js versions. Non-mutating toSorted() requires ES2023 (2023+ browsers).

100% Universal support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Array.sort() Excellent

Bottom line: Safe in every environment. Use a compare function for numbers; default string sort is the main beginner trap.

Conclusion

sort() reorders arrays in place. Default string sorting is fine for words but misleading for numbers—use (a, b) => a - b instead. Copy first when you must preserve the original order.

Next, learn splice() to add, remove, or replace elements at specific indices.

💡 Best Practices

✅ Do

  • Use (a, b) => a - b for numeric sort
  • Use localeCompare for locale-aware strings
  • Copy with spread before sorting if immutability matters
  • Keep compare functions pure (no side effects)
  • Sort objects by one clear field at a time

❌ Don’t

  • Rely on default sort() for multi-digit numbers
  • Forget that the original array is changed
  • Return non-numbers from compare (coerce to number)
  • Sort and assume order without storing the result
  • Confuse sort with reverse (flip vs reorder)

Key Takeaways

Knowledge Unlocked

Five things to remember about Array.sort()

Reorder elements with optional compare logic.

5
Core concepts
🔢 02

Default

String order.

Trap
💲 03

Numbers

a - b.

Compare
🔄 04

Mutates

In place.

Side effect
📦 05

Objects

By property.

Real world

❓ Frequently Asked Questions

sort() reorders the elements of an array in place and returns the same array reference. Without a compare function, elements are converted to strings and sorted by UTF-16 code unit values.
Yes. sort() changes the original array. If you need the original order preserved, copy first with spread ([...arr].sort()) or use the non-mutating toSorted() method (ES2023).
Default sort compares string versions: '100' comes before '40' because '1' < '4'. Always pass a compare function for numeric sorting: (a, b) => a - b.
Return a negative number if a should come before b, zero if equal order, positive if a should come after b. For numbers ascending: (a, b) => a - b. Descending: (a, b) => b - a.
reverse() only flips the current order end-to-end. sort() reorders elements by a comparison rule (default string order or your compare function).
sort() has been available since ES1 and works in all browsers including very old environments. Modern engines use a stable sort algorithm (ES2019 requirement).
Did you know?

Before ES2019, some JavaScript engines used unstable sorts—equal elements could swap order unpredictably. Today’s spec requires stability, so ties preserve their original relative order.

Continue to splice()

Learn how to add, remove, or replace elements at specific indices in one call.

splice() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful