Palindromic Number Triangle in JavaScript

What You’ll Learn
How to print a palindromic number triangle in JavaScript where each row increases from 1 up to the row number and then decreases back to 1.
This pattern is perfect practice for running two inner loops per row: one ascending, one descending.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
121
12321
1234321
123454321Complete JavaScript Program
First print 1..i. Then print i-1..1 so the middle digit isn’t duplicated.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= i; j++) {
line += j;
}
for (let k = i - 1; k >= 1; k--) {
line += k;
}
console.log(line);
}🧠 How It Works
Set the row count
const rows = 5; sets the triangle height.
Outer loop controls rows
for (let i = 1; i <= rows; i++) creates row 1 through row 5.
Ascending part (1..i)
for (let j = 1; j <= i; j++) appends numbers increasing from 1 to the row value.
Descending part (i-1..1)
for (let k = i - 1; k >= 1; k--) mirrors back down without repeating the middle digit.
Row becomes a palindrome
Because the second half is the reverse of the first half, the row reads the same both ways.
Variation — Browser (document.write) Version
Print the pattern directly into an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var rows = 5;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= i; j++)
document.write(j);
for (var k = i - 1; k >= 1; k--)
document.write(k);
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
rowsfor a bigger triangle - Add spaces between numbers for readability when rows exceed 9
- Center-align the triangle by printing leading spaces before each row
- Replace numbers with letters to form an alphabet palindrome pattern
Avoid
- Starting the second loop at
i(duplicates the middle digit) - Mixing row/column logic (keep the outer loop for rows)
- Forgetting the newline after each row
Key Takeaways
Each row is built from two parts: ascending then descending numbers.
Starting the reverse loop at i - 1 prevents duplicated centers.
This pattern demonstrates symmetry and mirroring with loops.
The same technique applies to diamonds and pyramid-style patterns.
❓ Frequently Asked Questions
1 2 3, then mirrors back with 2 1, producing 12321.rows - i spaces) to align the apex in the center." " after each number and use trim() or trimEnd() to remove the last extra space.padStart) so the triangle keeps its shape.Explore More JavaScript Number Patterns!
Try combining centering, spacing, and mirroring to create diamonds and pyramid patterns.
Many symmetry-based patterns are just an ascending loop followed by a descending loop. The key is choosing the correct start value for the reverse (often i - 1).
12 people found this page helpful
