write a loop which prints out an array backwards in javascript

You can print out an array backwards in Javascript by using a for loop and starting from the last index of the array, decrementing the index until you reach the first element. Here's an example:

index.tsx
let arr = [1, 2, 3, 4, 5];

for(let i = arr.length - 1; i >= 0; i--){
   console.log(arr[i]);
}
96 chars
6 lines

This will output:

index.tsx
5
4
3
2
1
10 chars
6 lines

In the loop, the i variable is initialized to the last index of the array using arr.length - 1. The loop then continues as long as i is greater than or equal to 0, and decrements i using i-- on each iteration. Finally, inside the loop, we can access the array elements using the current value of i with arr[i].

In this example, we're using console.log() to print out each array element to the console. You can modify the loop to do whatever you need with the array elements.

related categories

gistlibby LogSnag