Array sorting in JavaScript is used to arrange elements in a specific order, such as ascending or descending. The built-in sort() method helps organize data like numbers, strings, and objects, making it easier to display, search, and process information.


What Is Array Sorting?

Sorting means arranging elements in an order, such as:

  • Alphabetical order for strings

  • Numerical order for numbers

  • Custom order for objects

JavaScript provides the sort() method to sort array elements.


How sort() Works by Default

The sort() method converts elements to strings and compares them in Unicode order by default.

JavaScript
1let items = ["banana", "apple", "cherry"];
2items.sort();
3console.log(items);

Explanation:
Sorts strings alphabetically.


Sorting Numbers Correctly

By default, numbers are sorted as strings, which can give incorrect results. A compare function is used for numeric sorting.

JavaScript
1let numbers = [10, 2, 30, 4];
2numbers.sort((a, b) => a - b);
3console.log(numbers);

Explanation:

  • a - b sorts numbers in ascending order

  • Use b - a for descending order


Sorting in Descending Order

JavaScript
1let numbers = [5, 1, 10, 3];
2numbers.sort((a, b) => b - a);
3console.log(numbers);

Explanation:
Sorts numbers from largest to smallest.


Sorting Strings with Case Handling

JavaScript
1let names = ["apple", "Banana", "cherry"];
2names.sort((a, b) => a.localeCompare(b));
3console.log(names);

Explanation:
localeCompare() sorts strings correctly based on language rules.


Important Behavior of sort()

  • sort() modifies the original array

  • Returns a reference to the same array

  • Comparison logic must be provided for numbers

  • Works differently for strings and numbers


Common Mistakes with sort()

  • Expecting numeric sorting without a compare function

  • Forgetting that sort() mutates the original array

  • Sorting mixed data types without handling comparison logic

  • Assuming stable sort behavior across all environments


Summary of Array Sorting in JavaScript

TaskMethod
Sort stringssort()
Sort numbers ascendingsort((a, b) => a - b)
Sort numbers descendingsort((a, b) => b - a)
Case-aware string sortlocaleCompare()

Conclusion

Array sorting in JavaScript helps organize data for display and processing. By understanding how sort() works by default and how to use compare functions for numbers and custom sorting, arrays can be sorted accurately and efficiently in JavaScript applications.