Centered Hollow Number Diamond in JavaScript

What You’ll Learn
How to print a hollow number pyramid and then mirror it to form a centered hollow diamond.
It uses the same inner-gap idea as Program 57, plus a reversed loop for the bottom half.
⭐ Pattern Output
For n = 5, the pattern looks like this:
1
2 2
3 3
4 4
5 5
4 4
3 3
2 2
1Complete JavaScript Program
We build one function to print a single hollow row, then print rows 1..n and n-1..1.
const n = 5;
function makeRow(i) {
let line = " ".repeat(n - i);
if (i === 1) return line + "1";
return line + i + " ".repeat(2 * i - 3) + i;
}
for (let i = 1; i <= n; i++) console.log(makeRow(i));
for (let i = n - 1; i >= 1; i--) console.log(makeRow(i));🧠 How It Works
Row function
makeRow(i) prints indentation, then either a single 1 or two i values with a gap.
Top half (1..n)
Print rows from 1 to n to build the upper pyramid.
Bottom half (n-1..1)
Print rows from n-1 down to 1 to mirror the top half.
Inner gap formula
Row i has an inner gap of 2*i - 3 spaces.
Hollow diamond
Same row rule + mirrored rows creates the full diamond.
Variation — Browser (document.write) Version
Use so spacing doesn’t collapse in HTML:
<!DOCTYPE html>
<html>
<body>
<script>
var n = 5;
function printRow(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>");
}
for (var i = 1; i <= n; i++) printRow(i);
for (var i2 = n - 1; i2 >= 1; i2--) printRow(i2);
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
nto print a larger diamond - Replace numbers with
*to print a hollow star diamond - Use fixed-width padding for multi-digit n values
- Add a middle line (full numbers) to create a different style diamond
Avoid
- Using normal spaces in HTML (alignment breaks)
- Printing row 1 twice when mirroring (use n-1..1 for bottom)
- Forgetting the special case for i=1
Key Takeaways
Diamond height is 2n - 1.
Row i uses inner gap 2i - 3.
Mirror the top half with n-1..1 to avoid duplicating the center.
Use in HTML for consistent spacing.
❓ Frequently Asked Questions
" " per indentation step and adjust the inner-gap spaces accordingly.Explore More JavaScript Number Patterns!
Try filling this diamond (instead of hollow) by printing sequences across each row.
Most diamonds are just a pattern printed for 1..n and then repeated for n-1..1. Mirroring loops is a key pattern-printing skill.
12 people found this page helpful
