Reverse Ascending Number Triangle in JavaScript

What You’ll Learn
How to print a reverse ascending number triangle in JavaScript. Row length increases, but each row is printed in descending order.
This pattern is a useful variant for practicing opposite loop directions between outer and inner loops.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
21
321
4321
54321Complete JavaScript Program
Outer loop grows row size. Inner loop prints values from current row size down to 1.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = i; j >= 1; j--) {
line += j;
}
console.log(line);
}🧠 How It Works
Set total rows
const rows = 5; controls triangle height.
Outer loop (row growth)
for (let i = 1; i <= rows; i++) increases row length from 1 to rows.
Inner loop (print i..1)
for (let j = i; j >= 1; j--) appends descending values for that row.
Print row output
console.log(line); outputs one completed row each iteration.
Reverse ascending triangle
Total printed digits are triangular in count: n(n+1)/2, with overall complexity 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 = 1; i <= rows; i++) {
for (let j = i; j >= 1; j--) {
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Validate rows input before running nested loops
- Add spaces between digits for readability
- Use
rows = 8to see extended output - Swap inner loop direction to compare pattern differences
- Display output in the DOM instead of using
document.write
Avoid
- Using
j++in this reverse inner loop pattern - Forgetting newline output after each row
- Mixing row and column loop boundaries unintentionally
- Using
document.writein modern production interfaces
Key Takeaways
The outer loop controls row size growth.
The inner loop runs backward from i to 1.
Each row length increases by one while values descend.
Loop direction changes can generate entirely new pattern families.
❓ Frequently Asked Questions
j = i to 1, so values are printed in reverse order within each row.rows to at least 6. Then the last row will include 654321.console.log(line), as shown in Example 1.n(n+1)/2.Explore More JavaScript Number Patterns!
Try more loop combinations to quickly master row/column logic and output control.
Many interview pattern questions are solved by changing just one loop boundary or direction. This pattern is a perfect example of that principle.
12 people found this page helpful
