Juneikerc.com

How to reverse a number in JavaScript

featured image of post: How to reverse a number in JavaScript

In this tutorial, you will learn to reverse a number in js, for example, changing 123456789 to 987654321 in a very simple way.

Creating the function to reverse the number with JavaScript

js
const number = 123456789;
function reverseNumber(n) {
const convertAndReverse = n.toString().split("").reverse().join("");
return Number(convertAndReverse);
}
reverseNumber(number); // esto retorna 987654321

The reverseNumber function stores in the constant convertAndReverse what is necessary to reverse the number. Let's break down the entire code step by step.

1. Convert the number into a string

js
n.toString();

2- Convert the string of the number into an array

js
n.toString().split("");

3. Reverse it with the .reverse() method

js
n.toString().split("").reverse();

4. It is converted back into a string

js
n.toString().split("").reverse().join("");

To conclude, the function returns the value of convertAndReverse by passing it as a parameter to the Number method to convert it back into a number.

js
return Number(convertAndReverse);

Great, we're done, thank you very much for reading, I hope I have helped you.

Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me