revert array in javascript

To revert an array in JavaScript, you can use the reverse() method, which will reverse the elements of the original array, mutating it in place. Here is an example:

index.tsx
let myArray = [1, 2, 3, 4, 5];
myArray.reverse(); // Reverses the elements of "myArray" in place
console.log(myArray); // Outputs [5, 4, 3, 2, 1]
146 chars
4 lines

Alternatively, if you don't want to mutate the original array, you can create a new array with the elements in reverse order using the spread operator and the reverse() method. Here is an example:

index.tsx
let myArray = [1, 2, 3, 4, 5];
let reversedArray = [...myArray].reverse(); // Creates a new array with the elements of "myArray" in reverse order
console.log(myArray); // Outputs [1, 2, 3, 4, 5] (the original array is not mutated)
console.log(reversedArray); // Outputs [5, 4, 3, 2, 1]
286 chars
5 lines

gistlibby LogSnag