how to reverse a list in javascript

To reverse a list (or array) in JavaScript, we can use the reverse() method. This method reverses the order of elements in the array, and it modifies the original array.

Here's an example:

index.tsx
let myArray = [1, 2, 3, 4, 5];
myArray.reverse();
console.log(myArray); // Output: [5, 4, 3, 2, 1]
99 chars
4 lines

In the above code, we first define an array called myArray. Then, we call the reverse() method on myArray and store the reversed array back into myArray. Finally, we log the contents of myArray to the console, which should output [5, 4, 3, 2, 1] as expected.

Note that the reverse() method modifies the original array. If you don't want to modify the original array, you can make a copy of it first and then call the reverse() method on the copy.

index.tsx
let myArray = [1, 2, 3, 4, 5];
let reversedArray = myArray.slice().reverse();
console.log(myArray); // Output: [1, 2, 3, 4, 5]
console.log(reversedArray); // Output: [5, 4, 3, 2, 1]
182 chars
5 lines

In the above code, we first make a copy of myArray using the slice() method, and store it in a new array called reversedArray. Then, we call the reverse() method on reversedArray. Finally, we log both myArray and reversedArray to the console, which should output the original array followed by the reversed array.

gistlibby LogSnag