Reverse-Forward Number Triangle in JavaScript

What You’ll Learn
How to print a triangle where each row first counts down (from i to 2) and then counts up (from 1 to i).
This pattern creates symmetric rows like 32123 and 543212345 using two inner loops.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
212
32123
4321234
543212345Complete JavaScript Program
The first inner loop prints i, i-1, ..., 2. The second prints 1..i. Together they form the reverse-forward row.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = i; j > 1; j--) {
line += j;
}
for (let j = 1; j <= i; j++) {
line += j;
}
console.log(line);
}🧠 How It Works
Choose the row count
const rows = 5; sets how many rows are printed.
Outer loop builds each row
i goes from 1..rows, increasing the row width each time.
Print descending part (i..2)
for (j = i; j > 1; j--) prints the left portion without including 1.
Print ascending part (1..i)
for (j = 1; j <= i; j++) prints the right portion, completing the symmetric row.
Row is symmetric
The left half is descending and the right half is ascending, sharing a single 1 in the middle.
Variation — Browser (document.write) Version
Print the triangle in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 1; i <= 5; i++) {
for (j = i; j > 1; j--)
document.write(j);
for (j = 1; j <= i; j++)
document.write(j);
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
rowsfor a bigger triangle - Add spaces between digits (useful for multi-digit values)
- Center-align by adding leading spaces before each row
- Replace numbers with letters to build a similar alphabet pattern
Avoid
- Printing 1 in the first loop (it would duplicate the middle)
- Forgetting the newline after each row
- Mixing row and column roles across loops
Key Takeaways
Two inner loops build each row: one descending, one ascending.
Stopping the first loop at 2 prevents duplicating the center 1.
Rows are symmetric and grow with i.
This technique generalizes to many mirror-based patterns.
❓ Frequently Asked Questions
" " after each digit and trim at the end for clean formatting.Explore More JavaScript Number Patterns!
Mirror and palindrome patterns are excellent practice for controlling loop boundaries.
A tiny change in a loop boundary (like stopping at 2 instead of 1) can completely change whether the center value is duplicated. That’s why off-by-one logic matters a lot in pattern printing.
12 people found this page helpful
