sort()

ES3+

Sorts the elements of an array in place and returns the sorted array.

Syntax

array.sort(compareFunction)

Parameters

compareFunction Function optional

Function that defines the sort order

Return Value

Array

The sorted array

Examples

JavaScript
const numbers = [3, 1, 4, 1, 5, 9];
numbers.sort((a, b) => a - b);
console.log(numbers);
Output:
// [1, 1, 3, 4, 5, 9]

📌 When to Use

Use sort() when you need to arrange array elements in a specific order. Essential for sorting lists alphabetically, numerically, by date, or by any custom criteria. Remember it modifies the original array.

⚠️ Common Mistakes

Sorting numbers without a compare function: [10,2,1].sort() gives [1,10,2] (string sort!)

Forgetting that sort() modifies the original array - use toSorted() or [...arr].sort()

Inconsistent compare function: must return negative, zero, or positive consistently

✅ Best Practices

For numbers, always use a compare function: arr.sort((a, b) => a - b)

For case-insensitive string sort: arr.sort((a, b) => a.localeCompare(b))

Use toSorted() (ES2023) for immutable sorting in modern environments

⚡ Performance Notes

JavaScript sort() typically uses a variation of quicksort or mergesort with O(n log n) average complexity. It sorts in place, so no extra memory is needed for the array itself. For stable sorting (maintaining order of equal elements), use toSorted() in ES2023+.

🌍 Real World Example

Sorting Products by Multiple Criteria

Sort products by price (ascending) and then by name (alphabetically) for tied prices

const products = [
  {name: 'Banana', price: 1.50},
  {name: 'Apple', price: 1.50},
  {name: 'Cherry', price: 2.00}
];

// Sort by price, then by name
const sorted = [...products].sort((a, b) => {
  if (a.price !== b.price) {
    return a.price - b.price;  // Price ascending
  }
  return a.name.localeCompare(b.name);  // Name alphabetically
});
// [{name: 'Apple', price: 1.50}, {name: 'Banana', price: 1.50}, {name: 'Cherry', price: 2.00}]

Related Methods