We can use JavaScript to reverse a number easily by using converting the number into a string and then applying some JavaScript methods to reverse the string before we convert the string back to a number. We will make use of the JavaScript split(), reverse() and join() methods. Below is a function we will create to reverse a number.
function reverseNumber(num){
var stringNum = num + "";
var newStringArr = stringNum.split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
var backToNumber = Number(newStringArr);
return backToNumber;
};
And now we can simplify the function a little bit and give it a number to test with:
function reverseNumber(num){
var newStringArr = (num+"").split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return Number(newStringArr);
};
console.log(reverseNumber(456));
#Output:
654
So to recap, to reverse a number, we first have to convert it to a string. We can then use the split() method to get an array of each character in the string, and then use the reverse() method to return the array with all of the characters in reverse.
After reversing the array we then join the characters back together using the JavaScript join() method.
We finally convert the string back to a number using the Number() method.
Below is our function once again on how to reverse a number using JavaScript.
function reverseNumber(num){
var newStringArr = (num+"").split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return Number(newStringArr);
};
Note that if we tried to reverse a number like 100, we would get the follwoing:
function reverseNumber(num){
var newStringArr = (num+"").split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return Number(newStringArr);
};
console.log(reverseNumber(100));
#Output:
1
This happens because when we convert the String back to a Number, “001” is just the number 1. If we wanted to reverse a number with all of the digits included, we would have to return it as a string and not convert it to a number at the end.
Here would be the code to do that:
function reverseNumber(num){
var newStringArr = (num+"").split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return newStringArr;
};
console.log(reverseNumber(100));
#Output:
001
Hopefully this article has been helpful for you to learn how to use JavaScript to reverse a number.