JavaScript reverse() function returns an array that represents the array after it has been reversed. The reverse() function does not take any argument. To reverse the elements of the array, use the array reverse() function in JavaScript.
JavaScript reverse
JavaScript array reverse() is a built-in function that reverses the order of the elements in an array. The reverse() method will change the original array, which is why it is not a pure function.
The first array element becomes the last, and the last array element becomes the first due to the array reverse() method. The array reverse() method transposes the items of the calling array object in place, mutating the array and returning a reference to the array.
The reverse() is an intentionally generic method that can be called or applied to objects resembling arrays.
Objects which do not contain the length property reflecting the last in the series of consecutive, zero-based numerical properties may not behave in any meaningful manner.
Syntax
Now, see the following syntax of the method.
array.reverse()
How to reverse elements of array in JavaScript
To reverse an array elements in JavaScript, use the array.reverse() function.
let shows = ["Pink Panther", "Chhota Bheem", "Ben 10", "Tom and Jerry", "Doraemon"]; let output = shows.reverse(); console.log(output);
See the following output.
Reversing the elements in an array-like object
The following example creates an array-like object obj, containing three elements and a length property, then reverses the array-like object. The call to reverse() returns the reference to the reversed array-like object obj.
// app.js const obj = {0: 19, 1: 21, length: 3}; console.log(obj); Array.prototype.reverse.call(obj); console.log(obj);
See the following output.
So, this is how you can reverse the elements of an array.
The array reverse() function will reverse your array but modify the original. If you don’t want to alter the original array then you can do this:
function reverseArr(input) { var ret = new Array; for(var i = input.length-1; i >= 0; i--) { ret.push(input[i]); } return ret; } let arr = ["Pink Panther", "Chhota Bheem", "Ben 10", "Tom and Jerry", "Doraemon"] let op = reverseArr(arr); console.log(op);
See the following output.
That’s it for array reverse() in JavaScript.
thanks for the post