Reverse a number in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Our aim is to write a JavaScript function that takes in a number and returns its reversed number

For example, reverse of 678 −

876

Here’s the code to reverse a number in JavaScript −

Example

const num = 124323;
const reverse = (num) => parseInt(String(num)
.split("")
.reverse()
.join(""), 10);
console.log(reverse(num));

Output

Output in the console will be −

323421

Explanation

  • Let’s say num = 123
  • We convert the num to string → num becomes ‘123’
  • We split ‘123’ → it becomes [‘1’, ‘2’, ‘3’]
  • We reverse the array → it becomes [‘3’, ‘2’, ‘1’]
  • We join the array to form a string → it becomes ‘321’
  • Lastly we parse the string into a Int and returns it → 321
raja
Published on 18-Aug-2020 10:52:53
Advertisements