Inverted V-Shaped Hollow Star Pattern in JavaScript

What You'll Learn
This program prints a hollow inverted V (one star on top, then two stars farther apart each row). See Program 8 for the upright V (wide row first, vertex at the bottom).
Each row starts with spaces to shift the left edge, then one star; from row 2 onward, an inner gap of 2 * i - 3 (growing by 2 each row) and a second star.
⭐ Pattern Output
When you run the program with rows = 5:
*
* *
* *
* *
* *Complete JavaScript Program
Fixed rows = 5 version:
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let s = 1; s <= rows - i; s++) line += " ";
line += "*";
if (i > 1) {
for (let g = 1; g <= 2 * i - 3; g++) line += " ";
line += "*";
}
console.log(line);
}🧠 How It Works
Setup
const rows = 5; sets the height. for (let i = 1; i <= rows; i++) walks from the apex to the wide base; each iteration builds let line = "";.
Left margin and first star
for (let s = 1; s <= rows - i; s++) line += " "; shifts the row right. line += "*"; draws the left leg.
Gap and right star when i > 1
if (i > 1) { ... } runs for (let g = 1; g <= 2 * i - 3; g++) line += " "; for the hollow interior, then line += "*"; for the right leg. Row i === 1 is only the apex star.
Finish the line
console.log(line) prints the row with a newline. Each line has width 2 * rows - 1 characters.
Hollow inverted V
O(n²) output for n = rows, O(1) extra space. Width 2n - 1 scrolls in the green preview on phones.
💡 Tips for Enhancement
Try These
- Try Program 8 for the upright V (reverse the row loop)
- Combine Program 7 and Program 8 to form a hollow diamond (Program 9)
- Replace
*with#or@ - Increase
rowsand watch the gap expand by 2 each row - Print with spaces between stars for a wider look
Avoid
- Printing a second star on the first row (it would duplicate the top point)
- Using tabs for alignment (rendering differs)
- Mixing
with normal spaces (output becomes inconsistent) - Forgetting the inner-gap rule
2*i - 3 - Forgetting the line break after each row
Key Takeaways
Row i prints rows - i leading spaces.
Always print the first border star.
For i > 1, print an inner gap of 2*i - 3 spaces and a second star.
The inner gap grows by 2 each row.
Time complexity is O(n²) due to printing \(\Theta(n^2)\) characters.
❓ Frequently Asked Questions
2*i - 3 for row i (for i > 1).n rows, since total printed characters are \(\Theta(n^2)\).Next: V-Shaped Hollow
Continue to Program 8 to print a V-shaped hollow pattern (wide top, vertex at the bottom).
Hollow patterns are great practice for separating border printing from gap printing.
9 people found this page helpful
