How to Reverse Array in JavaScript
-
Reverse an Array Using the
reverse()
Function in JavaScript - Reverse an Array by Making Your own Function in JavaScript
This tutorial will discuss reversing an array using the reverse()
function and making our own JavaScript function.
Reverse an Array Using the reverse()
Function in JavaScript
If we want to reverse a given array, we can use the predefined function reverse()
in JavaScript. This function reverses the elements of a given array. For example, let’s define an array and reverse it using the reverse()
function and show the result on the console using the console.log()
function. See the code below.
var MyArray = [11, 12, 13, 14];
console.log('Original Array', MyArray)
MyArray.reverse();
console.log('Reversed Array', MyArray)
Output:
Original Array (4) [11, 12, 13, 14]
Reversed Array (4) [14, 13, 12, 11]
As you can see in the output, the original array is reversed. You can also reverse an array containing strings or objects.
Reverse an Array by Making Your own Function in JavaScript
If we want to make a function to reverse a given array, we can use a for
loop and the length
function in JavaScript. The length
function returns the number of elements of a given array. To make our function work, we have to get each element of the given array from the end, store it at the start in another array, and return it after the loop ends. Let’s make this function and test it with the array defined in the above method and show the result on the console using the console.log()
function. See the code below.
function ReverseArray(arr) {
var newArray = new Array;
var len = arr.length;
for (i = len - 1; i >= 0; i--) {
newArray.push(arr[i]);
}
return newArray;
}
var OriginalArray = [11, 12, 13, 14];
console.log('Original Array', OriginalArray);
var ReversedArray = ReverseArray(OriginalArray);
console.log('Reversed Array', ReversedArray);
Output:
Original Array (4) [11, 12, 13, 14]
Reversed Array (4) [14, 13, 12, 11]
As you can see in the output, the original array is reversed. You can also reverse an array containing strings or objects.
Related Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript