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.
Explanation:
-
a - bsorts numbers in ascending order -
Use
b - afor descending order
Sorting in Descending Order
Explanation:
Sorts numbers from largest to smallest.
Sorting Strings with Case Handling
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
| Task | Method |
|---|---|
| Sort strings | sort() |
| Sort numbers ascending | sort((a, b) => a - b) |
| Sort numbers descending | sort((a, b) => b - a) |
| Case-aware string sort | localeCompare() |
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.