Centered Palindromic Number Pyramid in JavaScript

What You’ll Learn
How to print a centered pyramid where each row is a palindrome: 1, then 1 2 1, then 1 2 3 2 1, and so on.
This pattern is perfect practice for nested loops, spacing, and symmetric output.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1Complete JavaScript Program
For each row i, we print indentation spaces, then numbers 1..i, then numbers i-1..1.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
// 2 spaces per indentation step
line += " ".repeat(rows - i);
for (let k = 1; k <= i; k++) {
line += k + " ";
}
for (let k = i - 1; k >= 1; k--) {
line += k + " ";
}
console.log(line.trimEnd());
}🧠 How It Works
Set the row count
rows = 5 controls the pyramid height.
Indentation spaces
" ".repeat(rows - i) adds fewer spaces as i increases, centering the pyramid.
Print ascending numbers
The first loop prints 1..i with spaces.
Print descending numbers
The second loop prints i-1..1 to complete the palindrome.
Palindromic row
A row is symmetric around the middle because we go up then back down.
Variation — Browser (document.write) Version
In HTML, use for spaces so the pyramid stays centered:
<!DOCTYPE html>
<html>
<body>
<script>
var rows = 5;
for (var i = 1; i <= rows; i++) {
for (var j = rows; j >= i; j--) document.write(" ");
for (var k = 1; k <= i; k++) document.write(k + " ");
for (var m = i - 1; m >= 1; m--) document.write(m + " ");
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
rowsto make the pyramid taller - Print without spaces to create a compact look (e.g.,
12321) - Use fixed-width formatting for multi-digit values (like
padStart) - Mirror the pyramid vertically to form a full diamond
Avoid
- Using normal spaces in HTML (they collapse); use
- Forgetting to trim trailing spaces in console output
- Printing
iagain in the descending loop (start fromi-1)
Key Takeaways
Each row is a palindrome: 1..i..1.
Indentation spaces are rows - i steps for centering.
Total values printed up to row n is n^2.
Use to preserve spacing in browser output.
❓ Frequently Asked Questions
i-1 so the peak value isn’t repeated.rows-1 back to 1 using the same row logic." ". For example, use line += k; instead of line += k + " ";.Explore More JavaScript Number Patterns!
Next, try printing the same pyramid as a full diamond by adding a mirrored bottom half.
Palindromic rows show up in many problems (numbers, strings, and arrays). Building a row up then down is a common technique.
12 people found this page helpful
