Mastering the sort() Method in JavaScript

Introduction

The sort() method in JavaScript is used to arrange the elements of an array in place, either in ascending or descending order. By default, it sorts elements as **strings** in Unicode code point order. 📊

📌 What is sort()?

sort() changes the original array by ordering its elements. You can also provide a custom comparison function for numerical or complex sorting.

  • ✔️ Sorts elements **in place** (modifies the array)
  • 📏 Defaults to string comparison, not numeric
  • 🔧 Accepts a custom compare function

💡 Syntax

Basic Syntax

array.sort(compareFunction)

Parameters:

  • compareFunction — (Optional) A function that defines sort order

🧵 Example: Default Sorting (Strings)

Sorting strings alphabetically

const fruits = ["banana", "apple", "cherry"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry"]

🔢 Example: Numeric Sorting

Note

Without a compare function, numbers will be sorted as strings — leading to unexpected results.

Sorting numbers correctly

const numbers = [40, 5, 100, 2];

// Wrong: Default sort
console.log(numbers.sort()); 
// [100, 2, 40, 5]

// Correct: Numeric sort
numbers.sort((a, b) => a - b);
console.log(numbers); 
// [2, 5, 40, 100]

⬇️ Descending Order

Descending numeric sort

const numbers = [40, 5, 100, 2];
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 5, 2]

⚠️ Important Notes

Note

  • sort() modifies the original array — clone it first if needed.
  • For consistent results, always provide a compare function when sorting numbers.
  • Sorting is not always stable in older JS engines, but modern ones generally are.

📊 Quick Reference Table

CodeOutput
["c", "a", "b"].sort()["a", "b", "c"]
[3, 1, 2].sort((a,b) => a-b)[1, 2, 3]
[3, 1, 2].sort((a,b) => b-a)[3, 2, 1]
>>"Sorting is the art of bringing order to chaos — and in JavaScript, sort() is your paintbrush."

🔥 Summary

The sort() method is a versatile way to order array elements. Always use a custom compare function for numbers or complex objects to avoid unexpected results.