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:

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:

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:

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:

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: