Filled Diamond Star Pattern in JavaScript

What You'll Learn
This program prints a filled diamond by combining a centered pyramid (upper half) and an inverted pyramid (lower half).
Upper half: i = 1..rows. Lower half: i = rows - 1..1. Each row prints rows - i spaces and 2*i - 1 stars.
⭐ Pattern Output
When you run the program with rows = 5:
*
***
*****
*******
*********
*******
*****
***
*Complete JavaScript Program
Fixed rows = 5 version:
const rows = 5;
function printPyramidRow(i, rows) {
let line = "";
for (let s = 1; s <= rows - i; s++) line += " ";
for (let j = 1; j <= 2 * i - 1; j++) line += "*";
console.log(line);
}
for (let i = 1; i <= rows; i++) {
printPyramidRow(i, rows);
}
for (let i = rows - 1; i >= 1; i--) {
printPyramidRow(i, rows);
}🧠 How It Works
printPyramidRow (one solid centered line)
function printPyramidRow(i, rows) clears line, adds rows - i spaces, then for (let j = 1; j <= 2 * i - 1; j++) line += "*";, then console.log(line). Every cell inside the outline is a star (unlike Program 9).
Upper half
for (let i = 1; i <= rows; i++) printPyramidRow(i, rows); grows odd star counts 1, 3, 5, … — same centering idea as Program 5.
Lower half
for (let i = rows - 1; i >= 1; i--) printPyramidRow(i, rows); reuses the same function so the middle row is not printed twice.
Lines, width, mobile
2 * rows - 1 lines total; widest row has 2 * rows - 1 stars. O(n²) output, O(1) extra space. Long rows scroll horizontally in the green preview on small screens.
Filled diamond
Solid odd-width rows stacked up then down. Optional one-liner per row: " ".repeat(rows - i) + "*".repeat(2 * i - 1).
💡 Tips for Enhancement
Try These
- Try Program 9 to print a hollow diamond outline
- Increase
rowsto make a larger diamond - Print spaces between stars using
"* ".repeat(2 * i - 1).trimEnd() - Replace
*with another character - Turn it into a double-diamond by printing two diamonds side by side
Avoid
- Printing the middle row twice (start lower half from
rows - 1) - Using tabs for alignment (rendering differs)
- Mixing
with normal spaces (output becomes inconsistent) - Using even star counts (breaks centering symmetry)
- Forgetting the line break after each row
Key Takeaways
Upper half prints i = 1..rows.
Lower half prints i = rows - 1..1 to avoid duplication.
Each row prints rows - i spaces and 2*i - 1 stars.
Odd star counts keep the shape symmetric.
Time complexity is O(n²) due to printing \(\Theta(n^2)\) characters.
❓ Frequently Asked Questions
n rows, since total printed characters are \(\Theta(n^2)\).Next: Hollow Diamond in Box
Continue to Program 11 to print a hollow diamond inside a square.
A filled diamond uses the same structure as a hollow diamond, but prints stars across the full width instead of only the borders.
9 people found this page helpful
