Rotating Number Pattern in JavaScript

What You’ll Learn
How to print a rotating number pattern where each row starts at the row number and wraps around to complete 1..5.
You’ll use two inner loops: one to print i..5 and one to print i-1..1.
⭐ Pattern Output
For size = 5, the pattern looks like this:
12345
23451
34521
45321
54321Complete JavaScript Program
First print from i to size. Then append the remaining values by printing from i-1 down to 1.
const size = 5;
for (let i = 1; i <= size; i++) {
let line = "";
for (let j = i; j <= size; j++) {
line += j;
}
for (let k = i; k > 1; k--) {
line += (k - 1);
}
console.log(line);
}🧠 How It Works
Set the size
const size = 5; defines the range 1..5.
Outer loop chooses the row start
i runs from 1..5, deciding the first digit of each row.
Print i..size
The loop j = i..size prints the increasing tail (e.g., 3 4 5).
Append i-1..1
The loop counts down and appends the remaining values, completing the wrap-around.
Row wraps cleanly
Start at 2, go to 5, then wrap back to 1.
Variation — Browser (document.write) Version
Print the pattern in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j, k;
for (i = 1; i <= 5; i++) {
for (j = i; j <= 5; j++)
document.write(j);
for (k = i; k > 1; k--)
document.write(k - 1);
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Make
sizelarger and print multi-digit values with spaces - Use arrays and modulo arithmetic to create other rotation patterns
- Reverse the second loop to change wrap direction
- Print separators between values for readability
Avoid
- Forgetting to update both loop bounds when changing size
- Printing without separators for multi-digit numbers (values can merge)
- Duplicating digits by using the wrong loop start/end
Key Takeaways
Two loops create the wrap-around: i..size then i-1..1.
Each row contains all digits 1..size exactly once.
Changing the loop boundaries changes the rotation behavior.
This is a great exercise for loop thinking and sequence generation.
❓ Frequently Asked Questions
i = 5, the first loop prints only 5, then the wrap loop appends 4 3 2 1." " after each value (and trim the end) for readability.Explore More JavaScript Number Patterns!
Wrap-around patterns help you practice building sequences in multiple stages.
Many “rotation” problems in programming can be solved either by slicing + concatenation, or by printing in two parts—exactly what we do here with two inner loops.
12 people found this page helpful
