Inverted Right-Aligned Triangle Star Pattern in JavaScript

What You'll Learn
This program prints an inverted, right-aligned triangle. Stars decrease each row, but the shape stays aligned to the right edge.
For row i (starting at 1), print i - 1 spaces, then print rows - 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 <= i - 1; s++) line += " ";
for (let j = i; j <= rows; j++) line += "*";
console.log(line);
}🧠 How It Works
Outer loop
for (let i = 1; i <= rows; i++) prints one line per row index. Each line still spans rows characters: growing padding on the left, shrinking star run on the right.
Growing left margin
for (let s = 1; s <= i - 1; s++) line += " "; prints i - 1 spaces (none on the first row).
Shrinking star run
for (let j = i; j <= rows; j++) line += "*"; prints rows - i + 1 stars. console.log(line) ends the row. Shorthand: " ".repeat(i - 1) + "*".repeat(rows - i + 1).
Inverted right-aligned triangle
O(n²) output for n = rows, O(1) extra space. Same character total as Programs 1–3; layout is the mirror of Program 3.
💡 Tips for Enhancement
Try These
- Try
" ".repeat(i - 1) + "*".repeat(rows - i + 1)as a shorter row builder - Compare with Program 3 to see how flipping star counts changes the shape
- Print spaces between stars using
"* ".repeat(rows - i + 1).trimEnd() - Try Program 5 (pyramid) after this to practice centered spacing
- Change the symbol from
*to#or@
Avoid
- Using tabs for alignment (rendering differs across editors)
- Printing extra spaces at the end of each line (harder to compare outputs)
- Mixing
with normal spaces (output becomes inconsistent) - Confusing
i - 1(spaces) withrows - i + 1(stars) - Leaving the output without line breaks (all stars appear on one line)
Key Takeaways
Row i prints i - 1 leading spaces.
Then it prints rows - i + 1 stars.
The triangle stays right-aligned because spaces increase as stars decrease.
repeat() can build rows in one expression.
Time complexity is O(n²) due to printing \(\Theta(n^2)\) characters.
❓ Frequently Asked Questions
i, print i - 1 spaces first, then print rows - i + 1 stars." ".repeat(i - 1) + "*".repeat(rows - i + 1).n rows, since printing spaces + stars across all rows is \(\Theta(n^2)\).Next: Pyramid
Continue to Program 5 to print a centered pyramid using spaces and odd stars.
Inverted patterns are a quick way to practice thinking in reverse: spaces usually increase while stars decrease.
9 people found this page helpful
