Descending Prefix Number Triangle in JavaScript

What You’ll Learn
How to print a descending prefix number triangle in JavaScript using nested loops. Each row starts from rows and expands by one value.
This pattern helps you practice loops where the start is fixed and the stop boundary shifts.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
5
54
543
5432
54321Complete JavaScript Program
Outer loop decreases row boundary, while inner loop prints from rows down to that boundary.
const rows = 5;
for (let i = rows; i >= 1; i--) {
let line = "";
for (let j = rows; j >= i; j--) {
line += j;
}
console.log(line);
}🧠 How It Works
Set row count
const rows = 5; defines top value and total rows.
Outer loop (boundary down)
for (let i = rows; i >= 1; i--) lowers the minimum value allowed in each row.
Inner loop (print rows..i)
for (let j = rows; j >= i; j--) prints descending values from top to current boundary.
Print each row
console.log(line); outputs one row at a time.
Descending prefix triangle
Total printed values follow triangular growth: 1+2+…+n = n(n+1)/2, so 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 = rows; j >= i; j--) {
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Validate input and prevent non-positive row values
- Add spaces between printed values for readability
- Set
rows = 7to see a larger triangle - Swap loop direction to produce mirrored variants
- Use DOM APIs instead of
document.writefor UI output
Avoid
- Using wrong inner loop stop conditions
- Forgetting row breaks after inner loop execution
- Mixing fixed start and shifting start logic accidentally
- Depending on
document.writein production pages
Key Takeaways
The outer loop shifts the lower boundary each row.
The inner loop always starts from a fixed top value.
Row length grows by one while values remain in descending order.
Small loop-boundary edits create many new pattern variants.
❓ Frequently Asked Questions
i = 3, so inner loop prints from 5 down to 3.54321 down to 5. Program 8 grows rows from 5 to 54321.console.log(line), which is better for algorithm practice.n(n+1)/2.Explore More JavaScript Number Patterns!
Keep experimenting with loop ranges to unlock more pattern combinations quickly.
Pattern programming is mostly about controlling loop start and end conditions. Master those, and most pattern questions become much easier.
12 people found this page helpful
