Reverse Repeated Number Triangle in JavaScript

What You’ll Learn
How to print a reverse repeated number triangle in JavaScript where row values decrease from rows to 1, while the row length increases.
This pattern helps you understand descending outer-loop control with a nested inner loop that repeats the current row value.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
5
44
333
2222
11111Complete JavaScript Program
The outer loop moves from rows down to 1. The inner loop repeats i exactly rows - i + 1 times.
const rows = 5;
for (let i = rows; i >= 1; i--) {
let line = "";
for (let j = rows; j >= i; j--) {
line += i;
}
console.log(line);
}🧠 How It Works
Set total rows
const rows = 5; sets the starting row value and total line count.
Outer loop (descending value)
for (let i = rows; i >= 1; i--) chooses the value to print on each line, from 5 down to 1.
Inner loop (repeat i)
for (let j = rows; j >= i; j--) runs more times as i gets smaller, and line += i; repeats the same digit.
Output each completed row
console.log(line); prints one row, then the loops continue until i reaches 1.
Reverse repeated number triangle
Total printed digits are 1+2+…+n = n(n+1)/2, so runtime is O(n²) for n rows.
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 = rows; j >= i; j--) {
document.write(i);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Accept
rowsas user input to generate dynamic pattern sizes - Add spaces between digits for cleaner output readability
- Convert this into an ascending variant by reversing outer-loop direction
- Render pattern inside a
<pre>element instead of usingdocument.write - Reuse the same loop logic for alphabet or symbol triangles
Avoid
- Printing
jwhen the pattern requires repeatedi - Forgetting to reset
lineinside the outer loop - Skipping input checks for invalid row values
- Using
document.writein production apps
Key Takeaways
The outer loop controls descending row values from rows to 1.
The inner loop repeats the same value, producing rows like 44 and 333.
Row length increases as the row value decreases.
Nested loops can produce many variants by changing loop direction and print value.
❓ Frequently Asked Questions
i = 5, inner loop runs once (j = 5), so only one digit is printed.i = 1, inner loop runs from j = 5 down to 1, so it prints 1 five times.console.log(line) for clean console output.Explore More JavaScript Number Patterns!
Practice reverse and forward pattern variations to strengthen your nested-loop skills.
This pattern combines two opposite ideas: the digit value decreases each row, but the row width increases. That contrast is a useful way to practice loop boundaries.
12 people found this page helpful
