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 and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.