Remove-Last-Digit Number Pattern in JavaScript

What You’ll Learn
How to print a number, then repeatedly remove its last digit and print again until it becomes 0.
This is a great warm-up for digit manipulation and while loops.
⭐ Pattern Output
For num = 86523, the output looks like this:
86523
8652
865
86
8Complete JavaScript Program
We print the current number, then update it using integer division by 10 until it becomes 0.
let num = 86523;
while (num !== 0) {
console.log(num);
num = Math.floor(num / 10);
}🧠 How It Works
Initialize num
num = 86523 is the starting value.
While num is not zero
The loop continues until all digits are removed.
Print current num
console.log(num) prints the current value on its own line.
Remove the last digit
Math.floor(num / 10) drops the last digit.
Digit reduction pattern
Each iteration prints a shorter number until only one digit remains.
Variation — Browser (document.write) Version
Print the pattern in the browser using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var num = 86523;
while (num != 0) {
document.write(num + "<br>");
num = Math.floor(num / 10);
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
numto print different digit reduction patterns - Use a do-while loop so 0 prints once (if you want)
- Try removing digits from the left using string slicing
- Count how many steps (digits) the number has while printing
Avoid
- Using floating-point division without
Math.floor(you’ll get decimals) - Forgetting the loop condition (could lead to infinite loop if num never changes)
- Using
document.writein production code (fine for tutorials)
Key Takeaways
Dividing by 10 and flooring removes the last digit.
A while loop naturally repeats until the number becomes 0.
This prints one line per digit removed.
The same technique is used in many digit-processing problems.
❓ Frequently Asked Questions
Math.abs(num) first, or handle the sign separately. The pattern is usually shown with positive numbers.do...while loop so the last value (0) prints once before the loop ends.s = s.slice(0, -1)).Math.floor(-1.2) becomes -2. If you want digit removal for negatives, work with Math.trunc or absolute values.Explore More JavaScript Number Patterns!
Try reversing this idea by building the number digit-by-digit instead of removing digits.
Removing digits with division is used in many problems like reversing numbers, counting digits, and checking palindromes.
12 people found this page helpful
