C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » JavaScript

JavaScript Reverse print an array

Here, we will learn how we can print the array elements in reverse order in JavaScript?
Submitted by Abhishek Pathak, on October 05, 2017

Arrays are an important data structures in any language. Reversing an array means printing the array elements in the reverse order.

Example:

var arr = [1,2,3,4,5];
var size = arr.length;
for(var i=size-1; i>=0; i--) {
  console.log(`Element ${i+1} is ${arr[i]}`);
}

Output

Element 5 is 5
Element 4 is 4
Element 3 is 3
Element 2 is 2
Element 1 is 1

Explanation

In the first line the array is defined. Then with the size variable, we will store the length of the array. After that, we traverse the loop in reverse order, which is starting with "size-1" index, which is 4 in our case and we are iterating till the 0th index. Inside the loop, we print or work on our element.

Easy in JavaScript? Stay tuned for more such tutorials.









COMMENTS