Descending Repeated Number Triangle in JavaScript

What You’ll Learn
How to print a descending repeated number triangle in JavaScript where each row repeats the same digit and the number of repeats decreases row by row.
This is useful for understanding how nested loops can control both row values and row width at the same time.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
55555
4444
333
22
1Complete JavaScript Program
Outer loop runs from rows down to 1. Inner loop prints the current row value i, exactly i times.
const rows = 5;
for (let i = rows; i >= 1; i--) {
let line = "";
for (let j = 1; j <= i; j++) {
line += i;
}
console.log(line);
}🧠 How It Works
Define rows
const rows = 5; sets the starting digit and total number of rows.
Outer loop (descending rows)
for (let i = rows; i >= 1; i--) chooses row values in descending order: 5, 4, 3, 2, 1.
Inner loop (print i times)
for (let j = 1; j <= i; j++) repeats the current digit i exactly i times.
Output one row at a time
console.log(line); prints each completed row and then moves to the next row.
Descending repeated triangle
Total digits printed are n+(n-1)+...+1 = n(n+1)/2, giving O(n²) time complexity.
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 = 1; j <= i; j++) {
document.write(i);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Allow users to input row count for dynamic output size
- Add separators (like spaces) for easier readability
- Switch to ascending loops to generate opposite triangle styles
- Render output in DOM elements instead of
document.write - Replace digits with letters or symbols for new pattern variants
Avoid
- Using the wrong inner-loop bounds for row length
- Printing
jwhen repeatediis expected - Skipping row resets when building line strings
- Using
document.writein production-grade UI code
Key Takeaways
The outer loop selects row value from high to low.
The inner loop prints each row value as many times as the row value itself.
Row width shrinks as values descend from 5 to 1.
Small loop-bound changes can produce entirely different pattern outputs.
❓ Frequently Asked Questions
i = 5, the inner loop runs five times, so it prints five 5s.rows = 7. The first line becomes 7777777 and then continues downward.document.write for browser output.n(n+1)/2.Explore More JavaScript Number Patterns!
Practice more descending and ascending triangle combinations to master nested loops quickly.
This pattern is the mirror counterpart of the repeated ascending triangle. Same concept, different loop direction and row shape.
12 people found this page helpful
