In this tutorial, we’ll learn how to reverse a number using JavaScript. This is a common programming exercise or interview question, as it tests your ability to manipulate numbers and strings.
JavaScript is a powerful scripting language that can handle this task easily. By the end of this tutorial, you’ll know how to reverse a number using different techniques in JavaScript.
Step 1: Convert the Number to a String
First, we need to convert the number to a string. This is because JavaScript strings have a built-in split()
method which can be used to break it into an array of single characters. We can achieve this by using the toString()
method to convert the given number to a string.
1 |
const number = 12345;<br>const numberAsString = number.toString(); |
Step 2: Split the String into an Array
Next, we’ll use the split()
method to convert the string into an array of single characters. This will make it easier to reverse the order of the characters.
1 |
const characters = numberAsString.split(''); |
At this point, characters
would be an array like:
['1', '2', '3', '4', '5']
Step 3: Reverse the Array
Now that we have the characters in an array, we can use the reverse()
method to reverse their order.
1 |
const reversedCharacters = characters.reverse(); |
reversedCharacters
would now be an array like:
['5', '4', '3', '2', '1']
Step 4: Join the Array Back into a String
With the characters reversed, we can use the join() method to combine them back into a single string.
1 |
const reversedNumberAsString = reversedCharacters.join(''); |
reversedNumberAsString
would now be a string:
'54321'
Step 5: Convert the Reversed String Back to a Number
Finally, we need to turn the reversed string back into a number. We can achieve this by using the parseInt()
function.
1 |
const reversedNumber = parseInt(reversedNumberAsString, 10); |
reversedNumber
would now be the number:
54321
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function reverseNumber(number) { const numberAsString = number.toString(); const characters = numberAsString.split(''); const reversedCharacters = characters.reverse(); const reversedNumberAsString = reversedCharacters.join(''); const reversedNumber = parseInt(reversedNumberAsString, 10); return reversedNumber; } const number = 12345; const reversedNumber = reverseNumber(number); console.log(reversedNumber); |
Output
54321
Conclusion
Congratulations! You have successfully learned how to reverse a number in JavaScript using different techniques.
While this might seem like a basic exercise, it is essential to understand how to manipulate numbers and strings for more complex coding tasks. Keep practicing and improving your JavaScript skills!