Inverted Right-Angled Triangle Star Pattern in JavaScript

What You'll Learn
This is the inverted version of Program 1. Start with rows stars on the first line and decrease by one star each row until you reach 1 star.
Total stars printed for rows = n is still \(n + (n-1) + \cdots + 1 = \frac{n(n+1)}{2}\).
⭐ 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 = rows; i >= 1; i--) {
let line = "";
for (let j = 1; j <= i; j++) line += "*";
console.log(line);
}🧠 How It Works
Countdown outer loop
for (let i = rows; i >= 1; i--) starts at the widest row and decreases i each time, mirroring Program 1’s geometry.
Inner loop: i stars
for (let j = 1; j <= i; j++) line += "*"; appends exactly i asterisks to line. Equivalent: line = "*".repeat(i);.
Print the row
console.log(line) sends each completed row to the console with a trailing newline.
Inverted triangle
Same total stars as Program 1: n(n+1)/2. O(n²) output, O(1) extra space. Wide first rows scroll horizontally in the green preview on small screens.
💡 Tips for Enhancement
Try These
- Use
"*".repeat(i)to build each row without an inner loop - Print the triangle with spaces between stars (e.g.,
"* ".repeat(i).trimEnd()) - Compare it with Program 1 to see the mirror effect
- Try right-aligned versions next (Program 3)
Avoid
- Counting the outer loop in the wrong direction (you must count down)
- Forgetting to print a newline per row
- Mixing tabs and spaces (alignment issues in other patterns)
- Printing extra spaces at the end of each line (harder to compare outputs)
Key Takeaways
Start with rows stars and decrease by 1 each row.
Total stars for n rows is \(n(n+1)/2\).
repeat() is a clean way to build rows without inner loops.
Time complexity is O(n²) because total printed characters grow quadratically.
This is the mirror of Program 1.
❓ Frequently Asked Questions
rows to 1."* ".repeat(i).trimEnd() for each row.n rows, because total printed characters are proportional to \(n(n+1)/2\).Next: Right-Aligned Triangle
Continue to Program 3 to print a right-aligned right-angled triangle.
When printing patterns in Node.js, building each row as a string and printing once per row is usually cleaner than multiple process.stdout.write calls.
9 people found this page helpful
