Home >>Javascript Programs >Reverse an array in JavaScript

Reverse an array in JavaScript

Reverse an array in JavaScript

JavaScript array reverse method is used to reverses the element of an array. If you are working with JavaScript then it’s important to know how to reverse an array. This article helps you how to reverse an array by using JavaScript. JavaScript makes it easy to build reverse an array.

In this method the arrays last elements become first and the first element becomes the last and if you have the middle element, doesn't require switch because it will be at the same position anyway. It helps you to changes the order of elements and returns the reverse sequence of the given array.

In this article, you will see what we will be going to do to solve the problems of reverse an array.

Methods

By using array.length property, you can also store the array length in size. After that, we run a for loop with 0 upto size/2, the other half elements are already swapped when once we reach half the array.

And the other method is simple to use and understand, you can only use JavaScript in-built function reverse() to reversing an array.

This article, helps you how to use method JavaScript reverse an array.

Let's take an example:

<!DOCTYPE html>
<html>
<body>
<button onclick="myarray()">Try it</button>
<p id="arynum"></p>
<script>
var numary = ["1", "2", "3", "4", "5"];
document.getElementById("arynum").innerHTML = numary;
function myarray() {
  numary.reverse();
  document.getElementById("arynum").innerHTML = numary;
}
</script>
</body>
</html>
Output:

 


No Sidebar ads