Write a program to reverse an array in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

We can reverse the array using reverse() method and also in a normal way.

Array.reverse()

Reversing Array using array.reverse() Method.

 Live Demo

Example

<html>
<body>
<script>
   var a = [1,2,3,4,5];
   a.reverse();
   document.write(a);
</script>
</body>
</html>

Output

5,4,3,2,1


Reversing Array without using any Built-in method.

 Live Demo

Example

<html>
<body>
<p id="reverse"></p>
<script>
   var t = [];
   var a = [1,2,3,4,5];
   for(var i = 0; i < a.length;i++){
   t[i] = a[a.length-1-i]
   }
document.getElementById("reverse").innerHTML = t;
</script>
</body>
</html>

Output

5,4,3,2,1
raja
Published on 22-May-2019 15:04:49
Advertisements