Centered Hollow Number Pyramid in JavaScript

What You’ll Learn
How to print a centered hollow pyramid where row i prints i on the left and right edges:
1, 2 2, 3 3, 4 4, 5 5.
⭐ Pattern Output
For n = 5, the pattern looks like this:
1
2 2
3 3
4 4
5 5Complete JavaScript Program
We print leading spaces for centering, then print i. For rows > 1, we print an inner gap and then print i again.
const n = 5;
for (let i = 1; i <= n; i++) {
let line = "";
// 1 leading space per step (matches the reference output style)
line += " ".repeat(n - i);
if (i === 1) {
line += "1";
} else {
const innerSpaces = 2 * i - 3;
line += i + " ".repeat(innerSpaces) + i;
}
console.log(line);
}🧠 How It Works
Set n
n = 5 controls pyramid height.
Leading spaces for centering
" ".repeat(n - i) shifts rows right so the pyramid is centered.
Row 1 prints only one digit
Row 1 has no inner gap, so we print just 1.
Rows 2..n print two digits
We print i, then 2*i - 3 spaces, then i again.
Hollow pyramid
Only the edges print numbers; everything inside is spaces.
Variation — Browser (document.write) Version
In HTML, use so spaces don’t collapse:
<!DOCTYPE html>
<html>
<body>
<script>
var n = 5;
for (var i = 1; i <= n; i++) {
for (var s = 1; s <= n - i; s++) document.write(" ");
if (i === 1) {
document.write("1");
} else {
document.write(i);
for (var gap = 1; gap <= 2 * i - 3; gap++) document.write(" ");
document.write(i);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
nto print a taller pyramid - Replace
iwith*to create a hollow star pyramid - Use fixed-width padding for multi-digit
ivalues - Add a mirrored bottom half to form a hollow diamond
Avoid
- Using normal spaces in HTML (alignment will break)
- Printing the second digit for row 1 (it duplicates the same position)
- Forgetting that the gap grows by 2 each row
Key Takeaways
Row 1 prints one digit; other rows print two.
Inner gap for row i is 2*i - 3 spaces.
Leading spaces are n - i for centering.
Use for browser-aligned output.
❓ Frequently Asked Questions
" " blocks) and adjust the formula accordingly.n-1 down to 1 after the top half.String(i) with "*" in both edge print positions.Explore More JavaScript Number Patterns!
Hollow patterns are great for practicing spacing rules. Next, try building a hollow diamond using the same inner-gap idea.
The inner gap grows by 2 because each new row adds one space on the left and one on the right of the “hollow” area.
12 people found this page helpful
