AppDividend
Latest Code Tutorials

JavaScript Array Reverse Example | JS Array Reverse() Method

0

JavaScript Array Reverse Example | JS Array Reverse() Method is today’s topic. JS reverse() method reverses the order of the items in an array. The Javascript array reverse() method will change the original array. The function returns an array which represents the array after it has been reversed. The reverse function does not take any argument.

JavaScript Array Reverse Example

The first array item becomes the last, and the last array element becomes the first due to array reverse() method in Javascript. The 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()

#Reversing the elements in an array

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, JS Array Reverse() Method Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

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