Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Sorting an Array

The sort() method arranges an array in alphabetical order.

const fruits = [“Banana”“Orange”“Apple”“Mango”];
fruits.sort();

Reversing an Array

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();

JavaScript Array toSorted() Method

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();

JavaScript Array toReversed() Method

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();