Array Methods in JS - reverse()

Shubham Tiwari - Aug 16 '22 - - Dev Community

Hello Guys today i will discuss reverse() array method in javascript
reverse() method is used to reverse array elements

Example -
[1,2,3,4,5]
After reversing
[5,4,3,2,1]

Let's get started...

Code Example 1 -

const numberArray = [1,2,3,4,5];
const stringArray = ['A','B','C','D','E'];
const booleanArray = [true,true,false,true,false];
const objectArray = [
  {
  name:"Shubham",
  age:21
  },
  {
  name:"Shivam",
  age:25
  },
  {
  name:"Bharat",
  age:22
  },
]
const mixedArray = [1,2,3,"A","B","C",true,false,
{
   name:"Shivam",
  age:25
}
]



console.log(numberArray.reverse())
console.log(stringArray.reverse())
console.log(booleanArray.reverse())
console.log(objectArray.reverse())
console.log(mixedArray.reverse())
Enter fullscreen mode Exit fullscreen mode

Output -

[ 5, 4, 3, 2, 1 ]
[ 'E', 'D', 'C', 'B', 'A' ]
[ false, true, false, true, true ]
[
  { name: 'Bharat', age: 22 },
  { name: 'Shivam', age: 25 },
  { name: 'Shubham', age: 21 }
]
[ { name: 'Shivam', age: 25 }, false, true, 'C', 'B', 'A', 3, 2, 1 ]

Enter fullscreen mode Exit fullscreen mode
  • As you can see we have reverses the arrays containing number, strings, booleans, objects and mixed.

Code Example 2 - How to reverse a string

const string = "hello"
const stringArray2 = []
for (let i of string){
  stringArray2.push(i)
}
stringArray2.reverse()
let reversedStr = stringArray2.join("").toString()
console.log(newStr)
Enter fullscreen mode Exit fullscreen mode

Output -

olleh
Enter fullscreen mode Exit fullscreen mode
  • As you can see first we have converted the string into array with each character as an element of array then we applied the reverse() method on this array.
  • After that we have used the join("").toString() to again convert the array into string again.

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .