Right-Aligned Descending Number Triangle in JavaScript

What You’ll Learn
How to print a right-aligned triangle where each row shows descending digits ending at 1: 1, 21, 321, 4321, 54321.
You’ll practice using a condition inside a loop to print either spacing or digits.
⭐ Pattern Output
For size = 5, the pattern looks like this:
1
21
321
4321
54321Complete JavaScript Program
The inner loop always counts from size down to 1. For early columns where j > i, we print spaces; otherwise we print the digit.
const size = 5;
for (let i = 1; i <= size; i++) {
let line = "";
for (let j = size; j >= 1; j--) {
line += (j > i) ? " " : String(j);
}
console.log(line.trimEnd());
}🧠 How It Works
Choose a size
const size = 5; sets both the height and the width of the triangle.
Outer loop builds rows
for (let i = 1; i <= size; i++) increases the number of printed digits each row.
Inner loop scans from size..1
for (let j = size; j >= 1; j--) ensures digits appear in descending order on each row.
Condition decides spaces vs digit
If j > i, we print spacing. Otherwise we print j.
Right-aligned row
Spaces come first, then the descending digits appear on the right.
Variation — Browser (document.write) Version
Print the pattern directly into an HTML page using document.write and spacing:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 1; i <= 5; i++) {
for (j = 5; j >= 1; j--) {
if (j > i)
document.write(" ");
else
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
sizeto create a bigger triangle - Print spaces between digits for larger sizes to improve readability
- Flip the loop direction to get an ascending right-aligned triangle
- Replace digits with symbols to create a right-aligned symbol triangle
Avoid
- Using normal spaces in HTML (use
for stable alignment) - Forgetting to trim trailing spaces in console output
- Mixing row/column roles (keep
ifor rows)
Key Takeaways
Leading spaces are produced by a simple condition (j > i).
Counting j downward prints digits in descending order.
The number of printed digits grows by one each row.
This is a common foundation for right-aligned pyramids and diamonds.
❓ Frequently Asked Questions
j <= 3 print, and the loop runs from 5 down to 1, so the printed digits are 3, 2, 1.j > i branch and just print j when j <= i.padStart) so multi-digit values don’t break alignment.Explore More JavaScript Number Patterns!
Right-aligned patterns teach spacing logic that you’ll reuse in pyramids and diamonds.
Most alignment problems in pattern printing come down to deciding when to print “padding” vs “content”. The j > i check here is a classic example.
12 people found this page helpful
