JavaScript reverse(): Reverse an Array

The JavaScript reverse() method is used to reverse an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const cities = ["Tokyo", "Bangkok", "Dubai", "Berlin", "London"];
      cities.reverse();
      document.getElementById("xyz").innerHTML = cities;
   </script>
   
</body>
</html>
Output

As you can see that this code is an example of using the reverse() method in JavaScript to reverse the order of elements in an array.

The code defines an array cities that contains five string elements. The reverse() method is then called on the cities array, which reverses the order of the elements in the array in-place.

Finally, the innerHTML property of the HTML element with id="xyz" is set to the reversed cities array, which is then displayed on the web page.

In this specific example, the original array ["Tokyo", "Bangkok", "Dubai", "Berlin", "London"] is reversed to ["London", "Berlin", "Dubai", "Bangkok", "Tokyo"], which is then displayed on the web page.

JavaScript reverse() syntax

The syntax of the reverse() method in JavaScript is:

array.reverse()

JavaScript reverse() example

Here is an example of the reverse() method that shows how we can use this method to reverse any array:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Original Array:-<br><span id="original"></span></p>
   <p>Array after Reverse:-<br><span id="reverse"></span></p>
   
   <script>
      const x = ["Tokyo", "Bangkok", "Dubai", "Berlin", "London"];
      document.getElementById("original").innerHTML = x;

      x.reverse();
      document.getElementById("reverse").innerHTML = x;
   </script>
   
</body>
</html>
Output

Original Array:-

Array after Reverse:-

The code defines an array of strings called "x" with 5 elements. It then displays the original array and the array after it has been reversed on an HTML page using the getElementById() and innerHTML properties. The reverse() method is called on the array x which reverses the order of its elements. The original array and the reversed array are displayed using the innerHTML property.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!