The sort() method arranges an array in alphabetical order.
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.sort(); |
The reverse() method inverses the order of elements in an array.
Example
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.reverse(); |
By employing both sort() and reverse(), you can arrange an array in descending order.
Example
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.sort(); fruits.reverse(); |
In ES2023, the toSorted() method was introduced as a secure alternative for sorting an array without modifying the original array.
The key difference between toSorted() and sort() is that the former method generates a new array, preserving the original array intact, whereas the latter method modifies the original array.
Example
const months = [“Jan”, “Feb”, “Mar”, “Apr”]; const sorted = months.toSorted(); |
In ES2023, the toReversed() method was introduced as a secure alternative for reversing an array without modifying the original array.
The key difference between toReversed() and reverse() is that the former method generates a new array, preserving the original array intact, whereas the latter method modifies the original array.
Example
const months = [“Jan”, “Feb”, “Mar”, “Apr”]; const reversed = months.toReversed(); |