JavaScript Array reverse() Tutorial

In this section, we will learn what the reverse() method is and how to use it in JavaScript.

JavaScript Arrays reverse() Method: Flip Backwards

The reverse() method is a way of reversing the elements of an array.

Basically, after applying this method to an array, those elements that were at the end of the array will move and take the first positions and those were in the first positions will be moved to the end of the array.

Note: this method changes the original array.

Array reverse() Syntax:

array.reverse()

Array reverse() Method Parameters:

The method does not take any argument.

Array reverse() Method Return Value:

The return value of the method is the reference to the array that we’ve run the `reverse()` method on.

Example: reverse an array in JavaScript

const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"];

arr.reverse();

console.log(arr);

Output:

["Twitter", "Facebook", "Amazon", "Microsoft", "Google", "Tesla"]

JavaScript Reverse String: How to Reverse a String in JavaScript?

In string, there’s no method like `reverse()` to apply to a string value in order to get the reverse version. But there’s a method called split() which will return an array of the target string with each character as one element in this array.

So what we can do here is to first turn a string value into an array and then run the `reverse()` method on it to reverse the elements.

Finally, in order to rejoin those elements into a string value, we can call the `join` method on the array.

Example: reverse a string in JavaScript

const val = "Reverse Me!";

const reversed = val.split("").reverse().join("");

console.log(reversed);

Output:

!eM esreveR
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies