AppDividend
Latest Code Tutorials

JavaScript Array Reverse Example | JS Array Reverse() Method

0

JavaScript Array reverse() is an inbuilt function that reverses the order of the items in an array. The reverse() method will change the original array that is why it is not a pure function. Javascript reverse() returns an array that represents the array after it has been reversed. The reverse function does not take any argument.

If you want to reverse the items of the array then Javascript array reverse() function does the job for you.

JavaScript array reverse example

Content Overview

The first array item becomes the last, and the last array element becomes the first due to the array reverse() method in Javascript.

JS 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.

Now, See the following syntax of the method.

array.reverse()

#How to reverse elements of array in Javascript

See the following code example.

let shows = ["Pink Panther", "Chhota Bheem", "Ben 10", "Tom and Jerry", "Doraemon"];
let output = shows.reverse();
console.log(output);

See the following output.

JavaScript Array Reverse Example

#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.

Reversing the elements in an array-like object

 

So, this is how you can reverse the items of an array.

The array reverse() function will reverse your array but modifying 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.

array reverse() function

Finally, JavaScript Array Reverse Example | JS Array Reverse() Method is over.

See also

Javascript array every()

Javascript array values()

Javascript array includes()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.