How to Reverse Array in JavaScript

Ammar Ali Feb 02, 2024
  1. Reverse an Array Using the reverse() Function in JavaScript
  2. Reverse an Array by Making Your own Function in JavaScript
How to Reverse Array 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.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - JavaScript Array