reverses the order of the elements in an array in javascript

To reverse the order of elements in an array in JavaScript, you can use the reverse() method. This method changes the original array and returns the reversed array.

Here's an example:

index.tsx
const arr = ['apple', 'banana', 'cherry', 'date'];

arr.reverse(); // ['date', 'cherry', 'banana', 'apple']
108 chars
4 lines

In this example, the reverse() method is called on the arr array, which reverses the order of the elements in the array. The original arr array is replaced with its reversed version.

If you don't want to modify the original array, you can create a new copy of the array and then reverse it using the slice() and reverse() methods like this:

index.tsx
const arr = ['apple', 'banana', 'cherry', 'date'];

const reversedArr = arr.slice().reverse(); // ['date', 'cherry', 'banana', 'apple']
136 chars
4 lines

In this example, the slice() method creates a new copy of the arr array, and then the reverse() method is called on the new array to reverse the order of its elements. The original arr array is not modified.

related categories

gistlibby LogSnag