Reverse an Array using JavaScript

This article I am going to show you the different way you can reverse an Array.

Array is a group of similar item, number etc that is store in single variable. For eg: let arr1 = [1,2,3]; This is an array example with a group of numbers.

There are multiple ways we can reverse an Array. One of the most easy way to do is to using array methods.

let x = [1,2,3,4,5,6];
let reverseX = x.reverse();  // prints [6, 5, 4, 3, 2, 1]

Reverse an Array using JavaScript swapping variable method

let x = [1,2,3,4,5,6];
let Xlen = x.length;

for(let i=0; i<n/2); i++){
     let startIndex = i;
     let endIndex = n-1 - i;
     let temp = a[endIndex];
     a[startIndex] = a[endIndex];
     a[endIndex] = temp;
}
console.log(x); // [6,5,4,3,2,1]

Leave a Reply

Your email address will not be published. Required fields are marked *