JavaScript Array sort()

sort() reorders the elements of an array in place. Without a compare function, JavaScript converts elements to strings and sorts them by UTF-16 code-unit order, so numeric arrays usually need an explicit comparator.

const numbers = [2, 22, 4, 24, 32];
numbers.sort((a, b) => a - b);
console.log(numbers); // [2, 4, 22, 24, 32]
JavaScript array elements before and after sorting

JavaScript sort() Syntax and Default Behavior Top ↑

array.sort()
array.sort(compareFn)

The optional compareFn(a, b) controls the order. If it is omitted, values are converted to strings for comparison. sort() returns the same array reference after sorting.

Sorting Strings with sort() Top ↑

The original page began with a simple alphabetical example:

const values = ["lmn", "ABC", "qwt"];
values.sort();
console.log(values);
["ABC", "lmn", "qwt"]

Default string ordering is based on UTF-16 code units, not a human-language dictionary order. Capitalization and accented characters can therefore affect the result.

Why Default Numeric Sorting Can Be Wrong Top ↑

The original page correctly showed that default sorting does not perform numeric comparison:

const numbers = [2, 22, 4, 24, 32];
numbers.sort();
console.log(numbers);
[2, 22, 24, 32, 4]

The values are compared as strings, so "32" comes before "4".

Sorting Numbers in Ascending and Descending Order Top ↑

const numbers = [2, 22, 4, 24, 32];

const ascending = [...numbers].sort((a, b) => a - b);
const descending = [...numbers].sort((a, b) => b - a);

console.log(ascending);  // [2, 4, 22, 24, 32]
console.log(descending); // [32, 24, 22, 4, 2]

Try the numeric ascending/descending demo.

How a sort() Compare Function Works Top ↑

The compare function receives two elements, commonly named a and b. Its return value determines their relative order.

  • Negative result: a comes before b.
  • Positive result: a comes after b.
  • Zero (or NaN): the values are treated as equal for ordering.
function compareNumbers(a, b) {
  return a - b;
}

const numbers = [2, 22, 4, 24, 32];
numbers.sort(compareNumbers);
console.log(numbers); // [2, 4, 22, 24, 32]

This is the modern simplified equivalent of the longer compare function used on the original page.

Sort Strings by Their Length Top ↑

The original page also sorted programming-language names by element length. That is a separate criterion from alphabetical order.

const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
scripts.sort((a, b) => a.length - b.length);
console.log(scripts); // ["PHP", "ASP", "HTML", "JavaScript"]

When lengths are equal, a stable sort preserves the earlier relative order of those equal-length values.

Try the string-length sorting demo.

Case-Insensitive and Locale-Aware String Sorting Top ↑

For user-facing text, localeCompare() is usually better than forcing strings to uppercase or lowercase and comparing code units manually.

const names = ["Émile", "alice", "Zoë", "bob"];
names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
console.log(names);

The exact order can depend on the locale and options you request.

Try the basic alphabetical sorting demo.

Sorting an Array of Objects Top ↑

const products = [
  { name: "Book", price: 250 },
  { name: "Pen", price: 20 },
  { name: "Bag", price: 800 }
];

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

For text properties, use a string comparator such as a.name.localeCompare(b.name).

sort() Changes the Original Array Top ↑

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

console.log(original); // [1, 2, 3]
console.log(sorted === original); // true
Mutation warning: if another part of your program shares this array reference, it sees the new order too.

Sort Without Mutating: toSorted() Top ↑

const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);

console.log(original); // [3, 1, 2]
console.log(sorted);   // [1, 2, 3]

toSorted() is the modern copying counterpart to sort(). A shallow-copy fallback is [...original].sort(compareFn).

JavaScript Array Sorting Is Stable Top ↑

Modern ECMAScript requires sort() to be stable: when the comparator considers two elements equal, their previous relative order is preserved.

const students = [
  { name: "Alex", grade: 15 },
  { name: "Devlin", grade: 15 },
  { name: "Sam", grade: 14 }
];

students.sort((a, b) => a.grade - b.grade);
console.log(students);

Alex remains before Devlin because both have the same grade and were already in that order.

undefined Values and Sparse Arrays Top ↑

With default sorting, undefined values move to the end without being passed to the compare function. Empty slots in sparse arrays are preserved and also move toward the end.

const values = ["b", undefined, "a"];
values.sort();
console.log(values); // ["a", "b", undefined]

JavaScript Array Sort Demos Top ↑

Alphabetical Sort Demo Sort by Length Numeric Ascending / Descending

You can also use reverse() to reverse an existing order, although a direct descending comparator is clearer for numeric sorting.

Common sort() Mistakes Top ↑

  • Calling sort() on numbers without a numeric comparator.
  • Forgetting that sort() mutates the original array.
  • Writing a comparator that returns only true/false instead of negative/positive/zero-style values.
  • Assuming default string sorting is locale-aware.
  • Doing expensive work repeatedly inside the comparator when the sortable key could be prepared once.
  • Using sort().reverse() when a descending comparator directly expresses the order.

Array Reference Display Array Elements




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer