Javascript provides the method reverse() to reverse the elements in an array such that the last element becomes the first element, the second last element becomes the second element and so on.

The reverse() method mutates the array. Let us look at some examples to demonstrate the method.

Reverse the elements in an array

We can call reverse() method using the dot notation on the array. Below we have an array numbers that contains integers. To reverse the array use the reverse() method as follows:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8];

console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8]

numbers.reverse();

console.log(numbers); // [8, 7, 6, 5, 4, 3, 2, 1]

Notice that the original array number gets changed when using the reverse method.

Reverse array-like objects

You can also use the reverse() method on array-like objects. To illustrate this let’s declare an array-like object and reverse it.

let data = {
    0: "zero",
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    length: 5
};

Array.prototype.reverse.call(data);

console.log(data); // {0: 'four', 1: 'three', 2: 'two', 3: 'one', 4: 'zero', 5: 'five', length: 5}