JavaScript Tutorials

JavaScript Array reverse()
Syntax & Examples

Array.reverse() method

The reverse() method of the Array class in JavaScript reverses the order of the elements of an array in place. This means that the first element becomes the last, and the last element becomes the first.


Syntax of Array.reverse()

The syntax of Array.reverse() method is:

reverse()

This reverse() method of Array reverses the order of the elements of an array in place. (First becomes the last, last becomes first.)

Return Type

Array.reverse() returns value of type Array.



✐ Examples

1 Using reverse() method to reverse the order of elements

In JavaScript, we can use the reverse() method to reverse the order of elements in an array.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the reverse() method on arr to reverse the order of elements in place.
  3. The order of elements in arr is reversed, and the array is updated accordingly.
  4. We log arr to the console using console.log() method to see the reversed order.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr);

Output

[5, 4, 3, 2, 1]

2 Using reverse() method with an array of strings

We can also use the reverse() method with an array of strings to reverse their order.

For example,

  1. We define an array variable strArr with elements ['apple', 'banana', 'cherry', 'date'].
  2. We use the reverse() method on strArr to reverse the order of strings in place.
  3. The order of strings in strArr is reversed, and the array is updated accordingly.
  4. We log strArr to the console using console.log() method to see the reversed order of strings.

JavaScript Program

const strArr = ['apple', 'banana', 'cherry', 'date'];
strArr.reverse();
console.log(strArr);

Output

['date', 'cherry', 'banana', 'apple']

Summary

In this JavaScript tutorial, we learned about reverse() method of Array: the syntax and few working examples with output and detailed explanation for each example.