TypeScript Array reverse()
Syntax & Examples
Array.reverse() method
The reverse() method reverses the order of the elements in an array in place and returns the reference to the same array, with its elements reversed.
Syntax of Array.reverse()
The syntax of Array.reverse() method is:
reverse(): T[]
This reverse() method of Array reverses the elements in an array.
Return Type
Array.reverse() returns value of type T[]
.
✐ Examples
1 Using reverse() to reverse a numeric array
The reverse() method can be used to reverse the order of elements in a numeric array.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Use
reverse()
to reverse the order of elements in the array. - Log the reversed array
arr
to the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr);
Output
[5, 4, 3, 2, 1]
2 Using reverse() to reverse a string array
The reverse() method can be used to reverse the order of elements in an array of strings.
For example,
- Create an array
arr
with string values ['apple', 'banana', 'cherry']. - Use
reverse()
to reverse the order of elements in the array. - Log the reversed array
arr
to the console.
TypeScript Program
const arr = ['apple', 'banana', 'cherry'];
arr.reverse();
console.log(arr);
Output
['cherry', 'banana', 'apple']
3 Using reverse() with a mixed data type array
The reverse() method can be used to reverse the order of elements in an array with mixed data types.
For example,
- Create an array
arr
with mixed values [1, 'apple', true, null]. - Use
reverse()
to reverse the order of elements in the array. - Log the reversed array
arr
to the console.
TypeScript Program
const arr = [1, 'apple', true, null];
arr.reverse();
console.log(arr);
Output
[null, true, 'apple', 1]
Summary
In this TypeScript tutorial, we learned about reverse() method of Array: the syntax and few working examples with output and detailed explanation for each example.