How to Reverse an Array in JavaScript Using Different Methods

In this article, we look at different methods to reverse an array elements using JavaScript. The array reverse() function in Javascript reverses the elements of an array. The first array element is replaced with the last, and the last is replaced with the first.

Method 01: Using the reverse method to Reverse an Array

As the name suggests, this method reverses the order of array elements by modifying the existing array.

Syntax:

array.reverse()

Example:

var arr = [1,2,3,4];
arr.reverse();
console.log(arr);

Output:

Using Reverse Method

Method 02: Using a decrementing For Loop to Reverse an Array

Example:

var arr = [1, 2, 3, 4];
var arr1 = [];
for (let i = arr.length - 1; i >= 0; i--) {
    arr1.push(arr[i]);
}
console.log(arr1);

We use a decrementing loop in the above example to traverse the array arr backward and put each entry in the new array arr1. The original array is not changed by this approach.

Output:

Using decrement for loop

Method 03: Using the Unshift() Method

Example:

var arr = [1, 2, 3, 4];
var arr1 = [];
arr.forEach(element => {
    arr1.unshift(element)
});
console.log(arr1);

This approach is identical to the previous one in that it does not change the original array. This approach uses the forEach() and unshift() functions instead of a for loop. The forEach() function performs an operation on each element of an array, whereas the unshift method adds a new element to the array’s beginning.

Output:

Using unshift method

Method 04: Without using a new array or the reverse() method

We did not alter the original array in the previous two ways, instead of storing the reversed elements in a new array. We’ll now examine how to change and reverse an existing array without utilizing the reverse function.

Example:

var arr = [1, 2, 3, 4];
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
    [arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]];
}
console.log(arr);

We only cover half of the length of the specified array in this technique, swapping items in equal distance from first and last, i.e. first element and last, second with second last, and so on.

Output:

Using new array

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. How to Reverse a String in JavaScript?
  2. What is the Callback Function in JavaScript?
  3. How to Paginate an Array in JavaScript?
  4. Unshift JavaScript Array Method – [With Examples]

Leave a Comment