JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to reverse an array in JavaScript?

JavaScript array has a reverse() function to reverse the order of elements of an array. The reverse() method changes the original array and also returns an array whose elements are in reverse order of the original array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let reversedarr = arr.reverse();
console.log('Reversed array', reversedarr);
console.log('Original array', arr);

Output

"Reversed array"
[9, 8, 7, 6, 5, 4, 3, 2, 1]
"Original array"
[9, 8, 7, 6, 5, 4, 3, 2, 1]

In the code above, you can see that the original array is also modified.

How to reverse an array without using reverse() method?

If you don't want to change the original array and cannot use reverse() method then use for loop to reverse the array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let reversedarr = [];
for(let i=arr.length-1; i>=0; i--){
  reversedarr.push(arr[i]);
}
console.log('Reversed array', reversedarr);
console.log('Original array', arr);

Output

"Reversed array"
[9, 8, 7, 6, 5, 4, 3, 2, 1]
"Original array"
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In the code above, the loop counter starts with the last element of the array and then it is decreased by 1 after each iteration. In each iteration, an element of the original array is accessed and pushed into another array.