Right-Aligned Triangle Star Pattern in JavaScript

What You'll Learn
This program prints a right-aligned triangle. Each row begins with some spaces so the stars line up to the right edge.
For row i (starting at 1), print rows - i spaces, then print i 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 <= i; j++) line += "*";
console.log(line);
}🧠 How It Works
Outer loop over rows
for (let i = 1; i <= rows; i++) drives one output line per iteration. let line = ""; accumulates characters left to right.
Leading spaces
for (let s = 1; s <= rows - i; s++) line += " "; prints rows - i spaces so the star block sits against the right for a fixed total width rows per line.
Stars and newline
for (let j = 1; j <= i; j++) line += "*"; adds i stars. console.log(line) prints the row. One-liner option: " ".repeat(rows - i) + "*".repeat(i).
Right-aligned triangle
O(n²) characters for n = rows, O(1) extra space. The green strip uses shared CSS so long lines scroll on touch devices.
💡 Tips for Enhancement
Try These
- Use
" ".repeat(rows - i) + "*".repeat(i)for clean code - Print spaces between stars using
"* ".repeat(i).trimEnd() - Compare with Program 1 to understand alignment vs. shape
- Try the inverted right-aligned triangle next (Program 4)
- Try the shorter version using
repeat()for both spaces and stars
Avoid
- Printing trailing spaces after the stars (can look odd in monospace output)
- Using tabs for alignment (rendering differs)
- Mixing spaces and other characters for indentation
- Printing extra spaces at the end of each line (harder to compare outputs)
Key Takeaways
Row i prints rows - i spaces and then i stars.
Leading spaces are what make the triangle right-aligned.
repeat() is a clean way to build each row.
Time complexity is O(n²) due to printing \(\Theta(n^2)\) characters.
This is the right-aligned variant of the basic triangle.
❓ Frequently Asked Questions
rows - 1 spaces so the single star sits at the right edge.i, print " ".repeat(rows - i) + "*".repeat(i).n rows, since printing spaces + stars across all rows is \(\Theta(n^2)\).Next: Inverted Right-Aligned
Continue to Program 4 to print the inverted right-aligned triangle.
Right-aligned patterns are a simple way to practice controlling leading spaces and understanding how alignment works in text output.
9 people found this page helpful
