reverse an array in javascript

There are several ways to reverse an array in JavaScript. One of the simplest ways is to use the built-in reverse() method that mutates the original array. Here's an example:

index.tsx
const array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array); // [5, 4, 3, 2, 1]
87 chars
4 lines

Note that reverse() reverses the elements in place and returns a reference to the original array, so there's no need to assign the result to a new variable.

If you want to create a reversed copy of the array without mutating the original one, you can use the slice() and reverse() methods together. Here's an example:

index.tsx
const array = [1, 2, 3, 4, 5];
const reversed = array.slice().reverse();
console.log(array); // [1, 2, 3, 4, 5]
console.log(reversed); // [5, 4, 3, 2, 1]
154 chars
5 lines

In this case, slice() creates a shallow copy of the array so that the original one is not affected, and then reverse() reverses the elements of the copied array.

Alternatively, you can use a for loop to copy the elements of the original array in reverse order into a new one. Here's an example:

index.tsx
const array = [1, 2, 3, 4, 5];
const reversed = [];
for (let i = array.length - 1; i >= 0; i--) {
  reversed.push(array[i]);
}
console.log(array); // [1, 2, 3, 4, 5]
console.log(reversed); // [5, 4, 3, 2, 1]
208 chars
8 lines

This approach is more verbose than the previous ones, but it also gives you more control over how the reversed array is created.

gistlibby LogSnag