Reverse Descending Number Triangle in JavaScript

What You’ll Learn
How to print a reverse descending number triangle in JavaScript using nested for loops. Each row starts from a decreasing value and counts down to 1.
This pattern is useful for learning how to control both a decreasing outer loop and a decreasing inner loop.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
54321
4321
321
21
1Complete JavaScript Program
The outer loop decreases the starting number each row. The inner loop prints from that value down to 1.
const rows = 5;
for (let i = rows; i >= 1; i--) {
let line = "";
for (let j = i; j >= 1; j--) {
line += j;
}
console.log(line);
}🧠 How It Works
Set the row count
const rows = 5; defines both the first row start and total rows.
Outer loop (rows down)
for (let i = rows; i >= 1; i--) reduces the row start value each iteration.
Inner loop (print i..1)
for (let j = i; j >= 1; j--) appends descending values from i down to 1.
Print one row per line
console.log(line); outputs each completed row on a new line.
Reverse descending triangle
Total printed digits are still triangular: 1+2+…+n = n(n+1)/2, so time complexity is O(n²).
Variation — Browser (document.write) Version
Print the same pattern directly in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
const rows = 5;
for (let i = rows; i >= 1; i--) {
for (let j = i; j >= 1; j--) {
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Add spaces between digits to improve readability
- Reverse the inner loop direction to get increasing rows
- Use user input to generate dynamic pattern sizes
- Replace digits with letters to build reverse alphabet patterns
Avoid
- Forgetting to decrement loop variables in reverse patterns
- Using wrong loop conditions that cause infinite loops
- Skipping newline output after each row
- Overusing
document.writein modern production pages
Key Takeaways
The outer loop moves from rows down to 1 and sets each row’s start value.
The inner loop prints from i down to 1 in reverse order.
Total printed digits still follow the triangular count: n(n+1)/2.
This reverse loop technique is helpful for star patterns and other mirrored designs.
❓ Frequently Asked Questions
rows (5) and the inner loop prints down from i to 1, so the first row becomes 54321.i becomes 4. Then inner loop j runs from 4 down to 1, producing 4321.line and print with console.log(line). This is generally cleaner for algorithm practice.n(n+1)/2.Explore More JavaScript Number Patterns!
Try more number pattern variations to master loop direction and boundary control.
Changing only loop direction can produce completely different visuals. Reverse loops are a core technique for mirrored and descending pattern problems.
12 people found this page helpful
