sort() & reverse() in JavaScript

From the JavaScript Array Methods cheat sheet · Array Manipulation · verified Jul 2026

sort() & reverse()

Sort and reverse array elements in place

javascript
// Sort (mutates array!)
arr.sort(); // Alphabetical
arr.sort((a, b) => a - b); // Numeric ascending
arr.sort((a, b) => b - a); // Numeric descending

// Reverse (mutates array!)
arr.reverse();

// Non-mutating versions
const sorted = [...arr].sort();
const reversed = [...arr].reverse();
⚠️ Both MUTATE the original array
💡 Use [...arr].sort() to avoid mutation
🔴 sort() converts to strings by default (10 < 2)
📌 Provide compare function for numbers: (a, b) => a - b
⚡ toSorted() and toReversed() are immutable (ES2023)

More JavaScript tasks

Back to the full JavaScript Array Methods cheat sheet