Growing Reverse Number Pattern in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
While Loop + Modulo

What You’ll Learn

Program 61 prints a growing reverse-number pattern: starting from an integer like 86523, build the reverse one digit at a time and print each partial result — 3, 32, 325, and so on. This tutorial covers modulo, reverse building, a live preview, worked JavaScript examples, edge cases, and O(d) complexity.

Shape Rule

Growing reverse

Each line adds one digit on the right of the partial reverse — 3 → 32 → 325 → 3256 → 32568.

While Loop

num !== 0

while (num !== 0) repeats once per digit until the source number is fully consumed.

Modulo

num % 10

num % 10 extracts the last digit — 3 from 86523, then 2 from 8652, and so on.

Build Reverse

reverse * 10 + digit

reverse = reverse * 10 + (num % 10) shifts left and appends the new digit on the right.

Live Preview

Any integer

Enter a starting number and watch the growing reverse pattern in the browser.

O(d)

Complexity

One iteration per digit — 86523 produces five lines; total steps equal digit count.

Introduction

A growing reverse number pattern builds the reversed form of an integer one digit at a time and prints each partial result. With num = 86523, you get 3, 32, 325, 3256, 32568.

In JavaScript use while (num !== 0), extract digits with num % 10, update reverse = reverse * 10 + digit, log with console.log(reverse), then num = Math.floor(num / 10).

Why it matters?

Modulo plus reverse building is the standard technique for reversing numbers, checking palindromes, and digit-sum problems.

Key Highlights

Extract digit

num % 10 — last digit each step.

Build reverse

reverse * 10 + digit appends on the right.

vs Program 60

Program 60 shrinks the original; Program 61 grows the partial reverse.

Series Foundation

Follow Program 60; continue to Program 62 next.

In short: while (num !== 0), reverse = reverse * 10 + num % 10, console.log(reverse), then num = Math.floor(num / 10).

📝 Problem & Approach

Given starting integer num = 86523, build its reverse one digit at a time and print each partial reverse until all digits are processed.

JavaScript
// num = 86523
//3
//32
//325
//3256
//32568

Inputs & Outputs

ItemTypeDescription
numnumberSource number — shrinks each iteration via Math.floor(num / 10).
reversenumberPartial reverse — starts at 0, grows each step.
Extract digitnumbernum % 10 — last digit of current num.
Append digitnumberreverse = reverse * 10 + digit.
Log stepvoidconsole.log(reverse) after each append.
Line countnumberEquals digit count of the starting number (86523 → 5 lines).

Minimal workflow

Pseudocode
reverse = 0
while num is not 0:
    digit = num % 10
    reverse = reverse * 10 + digit
    log reverse
    num = floor(num / 10)

Approach comparison

ApproachIdeaBest for
Two-step appendreverse *= 10 then reverse += digitTeaching each operation separately
Combined appendreverse = reverse * 10 + (num % 10)Compact production code
Math.abs + parseInt(prompt())Negative handling and user inputUser-input programs
Compact tracenum = 123 on paper firstQuick dry-runs
Arbitrary precisionJavaScript integers have no fixed limitVery large starting values

⚡ Quick Reference

GoalPattern
Loopwhile (num !== 0)
Extract digitdigit = num % 10
Append to reversereverse = reverse * 10 + digit
Log & shrinkconsole.log(reverse); num = Math.floor(num / 10)

📋 Fixed Value vs User Input vs Compact Trace

Same growing-reverse pattern — three ways to set the starting number and trace the logic.

Fixed value
let num = 86523;

Hard-coded start for demos

User input
parseInt(prompt())

Read starting number from console

Compact trace
let num = 123;

Quick dry-run on paper

Extract
num % 10

Last digit each step

Build
rev * 10 + d

Append digit on the right

Context

When This Pattern Shows Up

Reach for this pattern when teaching modulo, reverse building, and while loops together in JavaScript.

  1. Post Program 60 exercise

    Natural follow-up — same while loop, but build a growing reverse instead of shrinking the original.

  2. Number reversal drills

    Standard technique for reversing integers and checking palindromes.

  3. Interview warm-ups

    Classic modulo + division question — explain extract-append-shrink before coding.

  4. Gateway to Program 62

    Compare single-number loops with 2D spiral grid filling.

  5. Overflow awareness

    JavaScript integers have arbitrary precision — no overflow for typical inputs.

Key benefit: one small program that locks in modulo, reverse building, and O(d) thinking.

🔮 Live Preview

Enter a positive integer between 10 and 99999999 and draw the growing reverse pattern in the browser.

Try 123, 86523, or 9876. Max 8 digits in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed starting value, user input with abs, and a compact num = 123 trace. Click View Output to reveal sample console results.

📚 Getting Started

Print the growing reverse pattern for a hard-coded starting integer with a while loop.

Example 1 — Fixed num = 86523

Hard-coded start — build reverse one digit at a time and log after each append.

JavaScript
let num = 86523;
let reverse = 0;

while (num !== 0) {
  reverse = reverse * 10;
  reverse = reverse + (num % 10);
  console.log(reverse);
  num = Math.floor(num / 10);
}
Try it Yourself

How It Works

Extract 3 from 86523 → reverse becomes 3; then 2 → 32; then 5 → 325 — each line shows the partial reverse so far.

📈 Practical Variant

Read the starting number from the user and handle negatives with abs.

Example 2 — User Input Version

Read num with prompt(), validate with Number.isFinite, and use combined append in one expression.

JavaScript
const numInput = prompt("Enter a number:");
const parsed = parseInt(numInput, 10);

if (!Number.isFinite(parsed)) {
  console.log("Please enter a valid integer.");
} else {
  let num = Math.abs(parsed);
  let reverse = 0;

  while (num !== 0) {
    reverse = reverse * 10 + (num % 10);
    console.log(reverse);
    num = Math.floor(num / 10);
  }
}
Try it Yourself

How It Works

Same loop core as Example 1; combines multiply-and-add into one line and uses abs for negatives.

⚡ Compact Trace

Use num = 123 for a quick paper trace before larger demos.

Example 3 — Compact num = 123

Same while loop with a smaller starting value — easy to dry-run on paper.

JavaScript
let num = 123;
let reverse = 0;

while (num !== 0) {
  reverse = reverse * 10 + (num % 10);
  console.log(reverse);
  num = Math.floor(num / 10);
}
Try it Yourself

How It Works

Three iterations: extract 3 → reverse 3; extract 2 → reverse 32; extract 1 → reverse 321.

🧠 How the Algorithm Builds the Reverse

1

Set up

num is the source number; reverse starts at 0.

Setup
2

Extract last digit

num % 10 gives the current last digit (3, then 2, then 5, …).

Digit
3

Append to reverse

reverse = reverse * 10 + digit shifts existing digits left and appends the new one.

Build
4

Log and shrink num

console.log(reverse) then num = Math.floor(num / 10) moves to the next digit.

Step
=

Growing reverse pattern complete

One line per digit processed — O(d) time for d digits, O(1) extra memory.

🔎 Worked Walkthrough — num = 86523

Trace each loop iteration: extract the digit, update reverse, log, then shrink num.

StepnumDigit num % 10reverse after appendLogged
186523333
2865223232
38655325325
486632563256
5883256832568

Total lines logged: 5 = digit count of the starting number. Final reverse equals the full reversed number.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Modulo

num % 10 extracts digits — concrete introduction to the remainder operator.

Example: trace num = 123 and watch reverse grow 3, 32, 321.

2. Number Reversal

Standard building block for reversing integers and palindrome checks.

Example: stop after the loop and compare final reverse to the original.

3. Pair with Program 60

Program 60 shrinks the original; Program 61 grows the partial reverse — same loop, different output.

Example: log both patterns side by side for 86523.

4. Gateway to Program 62

Move from single-number loops to 2D spiral grid filling next.

Example: compare while-loop digit work with nested boundary loops.

5. Complexity Intuition

One iteration per digit — makes O(d) concrete for beginners.

Example: num = 1000000 produces seven lines — seven digits.

6. Input Validation Labs

Pair the pattern with parseInt(prompt()) and input validation.

Example: use long when reversed values may exceed int range.

Pro Tip: when an interviewer asks for reverse building, explain extract-append-shrink before writing the loop.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong append order or missing shrink shows up immediately as broken output.

  2. 2. Teaches Two Operators

    Modulo and integer division together — essential digit-manipulation toolkit.

  3. 3. Easy to Extend

    Print both num and reverse, collect steps in a list, or check palindromes with small edits.

  4. 4. O(1) Extra Memory

    Only num and reverse needed — no arrays required.

Pro Tip: trace num and reverse on paper for 123 before coding — watch reverse grow 3, 32, 321.

Usage Tips

Small habits that keep growing-reverse code clean.

  1. 1. Initialize reverse to Zero

    reverse = 0 before the loop — first digit becomes the first logged value.

  2. 2. Validate User Input

    Use Number.isFinite after parseInt(prompt()) for user input.

  3. 3. Multiply Before Adding

    reverse * 10 + digit — multiply shifts left, then append the new digit.

  4. 4. Shrink num Each Step

    num = Math.floor(num / 10) after logging — without it the loop never advances.

  5. 5. Dry-Run One Small Number

    Trace num = 123 on paper before coding larger demos.

Pro Tip: if reverse stays at single digits, you probably forgot to multiply by 10 before adding.

Common Pitfalls

Mistakes that commonly break growing-reverse patterns.

  1. 1. Forgetting to Multiply by 10

    Adding digits without shifting leaves reverse as single digits — 3, 2, 5 instead of 3, 32, 325.

    → Always do reverse = reverse * 10 + digit.

  2. 2. Not Shrinking num

    Without num = Math.floor(num / 10), the same digit is extracted forever — infinite loop.

    → Divide by 10 with Math.floor after each append and log.

  3. 3. Using / Instead of //

    num / 10 returns a float in JavaScript — the loop may behave unexpectedly.

    → Use num = Math.floor(num / 10) for integer digit removal.

  4. 4. Unchecked parseInt(prompt())

    Letters or empty input return NaN when parseInt(prompt()) is unchecked.

    → Validate with Number.isFinite and re-prompt on failure.

  5. 5. Using Floating-Point Math

    Float division on digits introduces precision errors — stick to integer operations.

    → Keep num and reverse as integer types.

Edge Cases

Check these inputs before calling the solution done.

num = 0

Zero input

while (num !== 0) never runs — log nothing or show a message.

num = 7

Single digit

One line prints 7 — simplest case.

120

Trailing zero

Builds 0, 2, 21 — zero is extracted first from the right.

Negative

Negative input

Apply Math.abs(num) before the loop — see Example 2.

Bad input

Non-numeric input

Bare parseInt(prompt()) returns NaN — validate with Number.isFinite.

Large n

Overflow risk

JavaScript integers have arbitrary precision — no overflow for typical inputs.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 60

  • Program 60 prints shrinking original
  • Program 61 prints growing partial reverse

2. Palindrome check

  • Build full reverse, then compare to original
  • Do not print intermediate steps

3. Next in series

  • Continue with Program 62
  • Perfect square spiral number pattern

4. Paper trace

  • Dry-run num = 123 before coding
  • Fill the walkthrough table by hand

Notes

  • Line count. Total lines equal the digit count of the starting number — hence O(d) time.
  • reverse * 10 shifts existing digits left before the new digit is appended on the right.
  • Use long when reversed values may exceed int.MaxValue.
  • Final reverse after the loop equals the fully reversed number — 32568 for input 86523.

Quick Takeaway: while (num !== 0), reverse = reverse * 10 + num % 10, log, then num = Math.floor(num / 10).

⏱️ Time and Space Complexity

ProgramTimeExtra space
While loop (Examples 1–2)O(d) — d = digit countO(1)
Compact trace (Example 3)O(d)O(1)
Wrap Up

🎉 Conclusion

The growing reverse number pattern is a small while-loop exercise with lasting payoff: modulo, reverse building, and O(d) intuition. Master the fixed-value version, then try user input with long and the compact num = 123 trace.

Practice the three examples above, then continue to Program 62 for the next pattern in the series.

Extract with modulo, append with multiply-and-add, log reverse, then shrink num — validate input when reading from prompt().

💡 Best Practices

✅ Do

  • Explain extract-append-shrink before coding
  • Initialize reverse = 0 before the loop
  • Use reverse = reverse * 10 + (num % 10)
  • Log reverse after each append
  • Use Number.isFinite after parseInt(prompt()) for user input
  • State O(d) time when asked about complexity

❌ Don’t

  • Forget to multiply reverse by 10 before adding
  • Skip num = Math.floor(num / 10) inside the loop
  • Use plain / without Math.floor for digit removal
  • Skip input validation when reading from the user
  • Skip the num = 123 dry-run before larger demos

Key Takeaways

Knowledge Unlocked

Five things to remember about this growing reverse pattern

Print the growing reverse pattern the beginner-friendly way.

5
Core concepts
% 02

Modulo

num % 10 extracts digit

Math
10 03

Append

reverse * 10 + digit

Code
04

Shrink

Math.floor(num / 10) each step

Loop
O 05

Complexity

O(d) time

Analysis

❓ Frequently Asked Questions

It prints a growing reverse-number pattern like 3, 32, 325, 3256, 32568 when starting from 86523.
It takes the last digit using num % 10 and appends it to reverse using reverse = reverse * 10 + digit, then logs reverse.
num = Math.floor(num / 10) removes the last digit so the loop can move to the next digit from the right.
Program 60 logs the shrinking original number. Program 61 builds and logs a growing partial reverse using modulo and multiplication.
Program 61 uses a single while loop on one number. Program 62 fills an n×n spiral grid with a 2D array.
Multiplying shifts existing digits left — reverse * 10 + digit appends the new digit on the right.
If the source number ends in 0, that digit is extracted last — e.g. 120 gives 0, 2, 21 (building from the right).
Apply Math.abs(num) before the loop — see Example 2.
O(d) where d is the number of digits — the loop runs once per digit.
Use parseInt with Number.isFinite after prompt(). Bare parseInt(prompt()) returns NaN on bad input.

Did you Know? 🔊

Each iteration takes the last digit with num % 10, appends it to reverse via reverse = reverse * 10 + digit, logs the partial reverse, then shrinks num with num = Math.floor(num / 10) — runtime is O(d) for d digits.

Continue to Program 62

Move on to the next pattern in the JavaScript number-pattern series.

Program 62 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful