• JavaScript Video Tutorials

JavaScript - TypedArray reverse() Method



The JavaScript TypedArray reverse() method is used to reverse the elements of the current typed array and returns a reference of the same typed array. Once the reverse process is over, the first typed array element becomes the last, and the last typed array element becomes the first.

Note − This method modifies the original typed array directly; no copy is made during the reversal process.

Syntax

Following is the syntax of JavaScript TypedArray reverse() method −

reverse()

Parameters

  • It does not accept any parameters.

Return value

This method returns a reference of the original typed array in reversed order.

Examples

Example 1

In the following program, we are using the JavaScript TypedArray reverse() method to reverse the elements of this typed array: [10, 20, 30, 40, 50].

<html>
<head>
   <title>JavaScript TypedArray reverse() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.write("TypedArray before reverse: ", T_array);
      
      //using reverse() method
      T_array.reverse();
      document.write("<br>TypedArray after reverse: ", T_array); 
   </script>    
</body>
</html>

Output

The above program returns a reverse typed array as [50, 40, 30, 20, 10].

TypedArray before reverse: 10,20,30,40,50
TypedArray after reverse: 50,40,30,20,10

Example 2

Here's another example of using the JavaScript TypedArray reverse() method. In this case, we create a button named "Reverse TypedArray" and use the onclick event to trigger an operation. Whenever users click on this button, the reverse() method will execute within the function, and the reversed typed array will be displayed in your window.

<html>
<head>
   <title>JavaScript TypedArray reverse() Method</title>
</head>
<body>
   <p id="before"></p>
   <p id="after"></p>
   <button onclick="Reverse()">Reverse TypedArray</button>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.getElementById("before").innerHTML = "TypedArray before reverse: " + T_array;
      function Reverse(){
         //using reverse() method
         T_array.reverse();
         document.getElementById("after").innerHTML = "TypedArray after reverse: " + T_array;
      } 
   </script>    
</body>
</html>

After executing the above program, an original TypedArray and a button will appear on your window. Once you click the button, the reversed TypedArray will be displayed.

Advertisements