Center-Aligned Pyramid Star Pattern in JavaScript

What You'll Learn
This program prints a center-aligned pyramid. Each row has an odd number of stars so the shape stays symmetric.
For row i (starting at 1), print rows - i spaces, then print 2*i - 1 stars.
⭐ Pattern Output
When you run the program with rows = 5:
*
***
*****
*******
*********Complete JavaScript Program
Fixed rows = 5 version (nested loops):
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let s = 1; s <= rows - i; s++) line += " ";
for (let j = 1; j <= 2 * i - 1; j++) line += "*";
console.log(line);
}🧠 How It Works
Outer row loop
for (let i = 1; i <= rows; i++) builds the pyramid from the apex upward. let line = ""; holds the current row.
Center with spaces
for (let s = 1; s <= rows - i; s++) line += " "; adds rows - i leading spaces so the star block stays centered for width 2 * rows - 1.
Odd-width star run
for (let j = 1; j <= 2 * i - 1; j++) line += "*"; prints 1, 3, 5, … stars. console.log(line) finishes the row.
Centered pyramid
O(n²) output for n = rows, O(1) extra space. Widest row has 2 * rows - 1 stars; it scrolls inside the green preview on narrow viewports.
💡 Tips for Enhancement
Try These
- Build rows with
" ".repeat(rows - i) + "*".repeat(2 * i - 1) - Print spaces between stars using
"* ".repeat(2 * i - 1).trimEnd() - Reverse the loop to create an inverted pyramid (Program 6)
- Try a hollow pyramid by printing only border stars
- Replace
*with another character (like#)
Avoid
- Using tabs for alignment (rendering differs across editors)
- Printing trailing spaces after the stars (can look odd in some outputs)
- Using even star counts (breaks centering symmetry)
- Mixing
with normal spaces (output becomes inconsistent) - Forgetting the line break after each row
Key Takeaways
Row i prints rows - i spaces for centering.
Then it prints 2*i - 1 stars (odd counts).
Odd stars keep the pyramid symmetric.
repeat() can build each row in one line.
Time complexity is O(n²) because printing dominates.
❓ Frequently Asked Questions
i prints rows - i spaces before the stars, shifting them into the center.n rows, since total printed characters are \(\Theta(n^2)\).Next: Inverted Pyramid
Continue to Program 6 to print the inverted pyramid by reversing the row loop.
The 2*i - 1 formula appears in many symmetric patterns because it grows by 2 each row.
9 people found this page helpful
