Skip to content

JavaScript Tutorial Arrays

JavaScript Array sort() and reverse()

Lesson 71 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

sort() changes the array, and sorts as text

By default sort() converts items to strings and compares them as text. That produces a surprising result for numbers.

script.js
JS
const numbers = [10, 9, 1, 100];
console.log(numbers.sort()); // → [1, 10, 100, 9]

“100” comes before “9” because the character “1” comes before “9”. It also mutates the original array.

The compare function

Pass a function (a, b) => ... that returns:

  • a negative number if a should come first,
  • a positive number if b should come first,
  • 0 if they are equal.

For numbers, subtraction does exactly this.

script.js
JS
const numbers = [10, 9, 1, 100];

numbers.sort((a, b) => a - b);
console.log(numbers); // → [1, 9, 10, 100]

numbers.sort((a, b) => b - a);
console.log(numbers); // → [100, 10, 9, 1]

Sorting objects

script.js
JS
const users = [
  { name: "Sam", age: 31 },
  { name: "Maya", age: 25 },
  { name: "Arjun", age: 28 }
];

users.sort((a, b) => a.age - b.age);
console.log(users.map(u => u.name)); // → ["Maya", "Arjun", "Sam"]

Sorting text for people

Use localeCompare, which understands language rules (accents, case).

script.js
JS
const names = ["Émile", "zoe", "Adam", "bob"];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // → ["Adam", "bob", "Émile", "zoe"]

A plain a < b comparison would put every capital letter before every lowercase letter.

reverse()

reverse() flips the order in place.

script.js
JS
const letters = ["a", "b", "c"];
letters.reverse();
console.log(letters); // → ["c", "b", "a"]

Keep the original: copy first

Because both methods mutate, make a copy when you need the original order:

script.js
JS
const original = [3, 1, 2];

const sorted = [...original].sort((a, b) => a - b);
console.log(sorted);   // → [1, 2, 3]
console.log(original); // → [3, 1, 2]

Newer browsers have toSorted() and toReversed() that do this for you, see Changing Arrays Without Mutating Them.

info
Sorting is stable
Modern JavaScript guarantees that items that compare as equal keep their original order. That makes sorting by one field after another predictable.