JavaScript - TypedArray toReversed() Method
The JavaScript TypedArray toReversed() method is used to copy the behavior (counterpart) of the reverse() method. When you invoke toReversed(), it creates a new typed array with the elements arranged in reverse order. Essentially, the last element becomes the first, and vice versa. Unlike reverse(), this method leaves the original typed array as it is.
The toReversed() method is specific to typed array instances (such as Uint8Array, Int16Array, etc.). Unlike the reverse() method, it does not modify the original array. On the other hand, the reverse() method is available for both regular arrays and typed arrays. When you call reverse() on an array, it modifies the original array and returns the array with its elements in reverse order.
Syntax
Following is the syntax of JavaScript TypedArray toReversed() method −
toReversed()
Parameters
It does not accepts any parameter.
Return value
This method returns a new typed array with elements in reverse order.
Examples
Example 1
In the following program, we use the JavaScript TypedArray toReversed() method to create a new typed array with elements in reversed order, taking an instance of the typed array [1, 2, 3, 4, 5].
<html>
<head>
<title>JavaScript TypedArray toReversed() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5]);
document.write("Typed array: ", T_array);
//using toReversed() method
const reverse_arr = T_array.toReversed();
document.write("<br>Reversed array: ", reverse_arr);
</script>
</body>
</html>
Output
The above program returns a new typed array with elements in reverse order as [5, 4, 3, 2, 1].
Typed array: 1,2,3,4,5 Reversed array: 5,4,3,2,1
Example 2
As we discussed earlier, the toReversed() method does not modify the original typed array; instead, it returns a new typed array with elements in reverse order.
The following is another example of the JavaScript TypedArray toReversed() method. We use this method to create a new typed array with elements in reverse order, after executing this program you can verify whether this modifies the original typed array.
<html>
<head>
<title>JavaScript TypedArray toReversed() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5]);
document.write("Typed array: ", T_array);
//using toReversed() method
const reverse_array = T_array.toReversed();
document.write("<br>Reversed array: ", reverse_array);
document.write("<br>Original array after reversed: ", T_array);
</script>
</body>
</html>
Output
After executing the above program, it will return new reversed typed array as −
Typed array: 1,2,3,4,5 Reversed array: 5,4,3,2,1 Original array after reversed: 1,2,3,4,5