javascript
  1. javascript-reverse

JavaScript reverse() Method

The JavaScript reverse() method is used to reverse the order of elements in an array. It modifies the original array and does not create a new one. The first element becomes the last and the last becomes the first, and so on.

Syntax

The syntax for the reverse() method is as follows:

array.reverse()

where array is the array to be reversed.

Example

Consider the following example:

let fruits = ["apple", "banana", "mango", "orange"];
fruits.reverse();
console.log(fruits);

Output:

["orange", "mango", "banana", "apple"]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reverse Fruits</title>
</head>
<body>

<!-- Display the original array of fruits -->
<p>Original Fruits: <span id="originalFruits"></span></p>

<script>
    // Original array of fruits
    let fruits = ["apple", "banana", "mango", "orange"];

    // Display the original array on the HTML page
    document.getElementById("originalFruits").textContent = fruits.join(", ");

    // Reverse the order of elements in the array
    fruits.reverse();

    // Display the reversed array on the HTML page
    document.write("<p>Reversed Fruits: " + fruits.join(", ") + "</p>");

    // Additional operations or code can be added here
    // For example, let's add a new fruit to the array
    fruits.push("grape");

 
</script>

</body>
</html>
Try Playground

Explanation

In the above example, we first declare an array fruits with 4 elements. We then call the reverse() method on it, which reverses the order of the array elements. When we log fruits to the console, we can see that the order of the elements has been reversed.

Use

The reverse() method is useful when you need to reverse the order of elements in an array. It can be helpful when you need to display items in descending order or when you need to perform a comparison of arrays from the end to the beginning.

Important Points

The following are some important points to consider when using the reverse() method:

  • The reverse() method modifies the original array and does not create a new one.
  • The reverse() method has a time complexity of O(n/2).
  • The reverse() method can be used on arrays of any data type, including strings and numbers.

Summary

The reverse() method in JavaScript is used to reverse the order of elements in an array. It modifies the original array and has a time complexity of O(n/2). The method can be useful when you need to display items in descending order or when you need to perform a comparison of arrays from the end to the beginning.

Published on: