Reversing Arrays in JavaScript

To reverse an array in JavaScript, you can use the array.reverse() method. The reverse() method allows you to reverse the order of the elements of an array so that the first element of the array becomes the last and the last element becomes the first. The reverse() method overwrites the original array. If the array is not contiguous (there are gaps between indices), then the reverse() method fills these gaps with elements with the value "undefined". You can also reverse the array manually using a for loop, but this will be slower than using the built-in array.reverse() method. In this JavaScript Array Reverse Example, we use the reverse() method to reverse an array. Below you can see more examples of reversing JavaScript arrays with a detailed description of each method. Click Execute to run the JavaScript Reverse Array Example online and see the result.
Reversing Arrays in JavaScript Execute
let array = ['JavaScript', 'Array', 'Reverse', 'Example'];

console.log(array.reverse());
Updated: Viewed: 7262 times

JavaScript array reverse() method

The array.reverse() method in JavaScript is used to reverse an array in place. The reverse() method reverses the array immediately; this means that the original elements of the array are swapped, and the original sequence is lost. You don't need to make a new variable to store a pointer to these arrays in memory since the original pointers already refer us to the reversed arrays.

JavaScript Array reverse() Syntax
array.reverse()

Where:
  • array: the array to be reversed
JavaScript Array Reverse Example
let array = ['25', '49', '19', '75'];

console.log(array.reverse());

// output: ['75', '19', '49', '25']

How to reverse array using for loop?

To reverse an array, you can also use a for loop to go through the elements of the array and create a new array in reverse order. The last element of the array will be the starting point of the loop, and it will be executed until it reaches the beginning of the array. Unlike the array.reverse() method, this solution does not change the original array. A new array is created containing the elements in reverse order. Note that this method is slower and takes up extra memory space.

JavaScript Array Reverse with for loop
let array = ['JavaScript', 'Array', 'Reverse', 'Example'];
let newArray = [];

for(i = array.length-1; i >= 0; i--) {
  newArray.push(array[i]);
}

console.log(newArray);

// output: ['Example', 'Reverse', 'Array', 'JavaScript']

See also