• JavaScript Video Tutorials

JavaScript - Array reverse() Method



In JavaScript, the Array.reverse() method is used to reverse the order of the elements present in an array. In other words, the first element will become the last, and the last element will become the first element. This method overwrites the original array.

If we want to reverse the elements in an array without mutating the original array, use the JavaScript Array.toReversed() method.

Syntax

Following is the syntax of JavaScript Array reverse() method −

array.reverse();

Parameters

This method does not accept any parameters.

Return value

This method reverses the elements of an array in place (mutates the original array). The return value is the reversed array.

Examples

Example 1

In the following program, we are using the JavaScript Array reverse() method to reverse the elements order in the array.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      document.getElementById("demo").innerHTML = animals.reverse();
   </script>
</body>
</html>

Output

As we can see in the output, the array elements order has been reversed.

Elephant,Tiger,Cheetah,Lion

Example 2

If the array is empty and we try to use the reverse() method on it, this method will return will return nothing as output.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = [];
      document.getElementById("demo").innerHTML = animals.reverse();
   </script>
</body>
</html>

As we can see in the output, nothing is returned.

Advertisements