Use the reverse() method to reverse an array in JavaScript. This method reverses the order/sequence of the elements in an array. Note it will change the original array.
Syntax
array.reverse()
Return value
Reversed elements array.
Example of JavaScript Reverse Array
Let’s see an example to reverse the sequence of elements of the array in JS
<!DOCTYPE html>
<html>
<body>
<script>
var arr1 = ["A", "B", "C", "D"];
alert(arr1.reverse())
</script>
</body>
</html>
Output:
How to reverse array without modifying in JavaScript?
You can Reverse array in JavaScript without mutating the original array use slice() to make a copy then reverse() it.
var newarray = array.slice().reverse();
Reverse an array in JavaScript without reverse function
An array.pop() removes the popped element from the array, reducing its size by one. Once you’re at i === middle_element, your break condition no longer evaluates to true and the loop ends.
function reverse(array) {
var output = [];
while (array.length) {
output.push(array.pop());
}
return output;
}
console.log(reverse([1, 2, 3, 4, 5, 6, 7]));
Do comment if you have any questions and suggestion on this tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version