Reverse-Build Number Pattern in JavaScript

What You’ll Learn
How to build the reverse of a number one digit at a time and print each intermediate result.
This pattern is essentially the number-reversal algorithm, but we print at each step to form a pattern.
⭐ Pattern Output
For num = 86523, the output looks like this:
3
32
325
3256
32568Complete JavaScript Program
Take the last digit with % 10, append it to reverse, print, then drop the digit from num.
let num = 86523;
let reverse = 0;
while (num !== 0) {
reverse = reverse * 10 + (num % 10);
console.log(reverse);
num = Math.floor(num / 10);
}🧠 How It Works
Initialize num and reverse
num = 86523, reverse = 0.
Extract the last digit
digit = num % 10 returns the last digit.
Append digit to reverse
reverse = reverse * 10 + digit appends the new digit.
Print and reduce num
Print reverse, then remove the last digit using Math.floor(num / 10).
Pattern emerges
Each step adds one more digit to the reversed number until the full reverse is formed.
Variation — Browser (document.write) Version
Print the intermediate reverse values in the browser:
<!DOCTYPE html>
<html>
<body>
<script>
var num = 86523;
var reverse = 0;
while (num != 0) {
reverse = reverse * 10 + (num % 10);
document.write(reverse + "<br>");
num = Math.floor(num / 10);
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
numand observe how the reverse grows each step - Use
Math.truncinstead ofMath.floorif you plan to handle negative numbers - Print both
numandreverseeach iteration for debugging - After the loop, print the final reverse on a separate line
Avoid
- Using
document.writein production apps (fine for demos) - Forgetting to update
num(would cause an infinite loop) - Using floating-point values for
num
Key Takeaways
num % 10 gives the last digit.
reverse = reverse * 10 + digit appends digits to build the reverse.
Math.floor(num / 10) removes the last digit from the original number.
Printing each intermediate reverse creates the pattern.
❓ Frequently Asked Questions
reverse at every step to form a pattern.reverse first, then print.s.slice(0, i)) to grow from the left.Want More Digit Patterns?
Try printing the number as it shrinks (Program 60) and compare it with this growing reverse output.
The modulo operator % is one of the most common tools for digit extraction problems.
12 people found this page helpful
