What is the array.reverse() method in TypeScript?
Overview
It is easy to reverse an array in TypeScript using the reverse() method. We can also do this in JavaScript. As a general rule, whatever we can do in JavaScript, we can also do in TypeScript, in addition to being able to do much more.
Syntax
array.reverse()
Reverse an array in TypeScript
Parameters
The reverse() method requires an array as a parameter, which we want to reverse.
Return value
This method returns an array with all its elements in a reversed order.
Code example
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let numbers : Array<number>;numbers = [12, 34, 5, 0.9]let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]let randomValues : Array<string | number> = ["one",1, "two", 2, 56]// reverse the arrays and print the resultsconsole.log(names.reverse())console.log(numbers.reverse())console.log(cars.reverse())console.log(randomValues.reverse())
Explanation
- Lines 2–6: We create some arrays in TypeScript.
- Lines 9–12: We apply the
reverse()method to all the created arrays and display their results on the screen.