Rotated Number Sequence Pattern in JavaScript

What You’ll Learn
How to print a 5×5 pattern where each line is a rotated-looking number sequence:
12345, 21234, 32123, 43212, 54321.
⭐ Pattern Output
For n = 5, the pattern looks like this:
12345
21234
32123
43212
54321Complete JavaScript Program
For each row i, we print a short descending sequence from i down to 2, then an ascending sequence from 1 up to n + 1 - i.
const n = 5;
for (let i = 1; i <= n; i++) {
let line = "";
for (let j = i; j > 1; j--) {
line += j;
}
for (let k = 1; k <= n + 1 - i; k++) {
line += k;
}
console.log(line);
}🧠 How It Works
Set n
n = 5 prints 5 lines of 5 digits.
Row loop (i)
Each row uses its index i to decide what prefix to print.
Descending prefix (i..2)
The first inner loop prints i, i-1, … down to 2.
Ascending tail (1..n+1-i)
The second inner loop prints the remaining digits to keep each row length equal to n.
Rotated-looking sequence
A decreasing prefix + increasing tail creates the rotated effect.
Variation — Browser (document.write) Version
Print the same pattern in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var n = 5;
for (var i = 1; i <= n; i++) {
for (var j = i; j > 1; j--)
document.write(j);
for (var k = 1; k <= n + 1 - i; k++)
document.write(k);
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
nto print more (or fewer) rows - Add spaces between digits to improve readability
- Print the pattern as a 2D array first, then join into lines
- Try starting the ascending tail from 0 to create a new variant
Avoid
- Off-by-one mistakes in the second loop (it must be
n + 1 - i) - Forgetting the line break after each row
- Mixing string concatenation and numeric math without converting types
Key Takeaways
Each row is built from two parts: decreasing prefix + increasing tail.
The decreasing part runs from i down to 2.
The increasing part runs from 1 up to n + 1 - i.
Two small loops can create many “rotated” number sequence patterns.
❓ Frequently Asked Questions
i = 1, the loop for (j = i; j > 1; j--) doesn’t run, so the row is just 12345.j + " " and k + " " instead of concatenating digits directly.n in all loop bounds and make the second loop end at n + 1 - i.Explore More JavaScript Number Patterns!
Once you’re comfortable building rows from multiple loops, try combining spaces + numbers to make centered and diamond patterns.
Many “rotation” patterns are really just reordered concatenations of a decreasing part and an increasing part.
12 people found this page helpful
