Reverse array with for loops JavaScript


We have to write a function that takes in an array and returns its reverse. Find its reverse using the for loop.

Our sample array −

const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];

So, let’s write the code for this function −

Example

const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
const reverse =(arr) => {
   const duplicate = arr.slice();
   const reversedArray = [];
   const { length } = arr;
   for(let i = 0; i < length; i++){
      reversedArray.push(duplicate.pop());
   };
   return reversedArray;
};
console.log(reverse(arr));

Output

The output in the console will be −

[
   6, 43, -12, 12, 8,
   7, 5, 4, 3, 2,
   7
]

Updated on: 21-Aug-2020

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements