Right-Aligned 5-to-i Descending Triangle in JavaScript

What You’ll Learn
How to print a right-aligned triangle where each row starts at 5 and prints down to the row limit: 5, 5 4, 5 4 3, 5 4 3 2, 5 4 3 2 1.
You’ll practice indentation with spaces and a descending loop for the numbers.
⭐ Pattern Output
For size = 5, the pattern looks like this:
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1Complete JavaScript Program
First, print indentation spaces. Then print numbers from size down to i. As i decreases, each row gets longer.
const size = 5;
for (let i = size; i >= 1; i--) {
let line = "";
for (let s = 1; s < i; s++) {
line += " ";
}
for (let j = size; j >= i; j--) {
line += j + " ";
}
console.log(line.trimEnd());
}🧠 How It Works
Set the size
const size = 5; sets the maximum number and the height.
Outer loop controls row limit
i counts down from 5 to 1. Smaller i means more numbers printed.
Indentation spaces
The loop s = 1..i-1 prints spaces so earlier rows shift to the right.
Print numbers size..i
for (j = size; j >= i; j--) prints 5 4 3 ... down to i on each row.
Right-aligned triangle
Spaces shrink while the descending sequence grows.
Variation — Browser (document.write) Version
Print the same output inside an HTML page using for indentation:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 5; i >= 1; i--) {
for (j = 1; j < i; j++)
document.write(" ");
for (j = 5; j >= i; j--)
document.write(j + " ");
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Make
sizedynamic and print fromsizedown to 1 - Change the number loop direction to build other right-aligned triangles
- Use fixed-width padding for multi-digit sizes (alignment stays clean)
- Center-align by printing more spaces and using two halves
Avoid
- Using normal spaces in HTML (use
for stable indentation) - Forgetting to add a newline /
<br>after each row - Mixing string concatenation and numbers without separators
Key Takeaways
Indentation is created by a loop that prints spaces before the digits.
The number loop prints a descending range from 5 down to i.
As i decreases, the triangle grows wider.
This is a common base for right-aligned and centered patterns.
❓ Frequently Asked Questions
i = 5, so the number loop prints from 5 down to 5 (one value).trimEnd() to remove extra spacing.Explore More JavaScript Number Patterns!
Indentation-based patterns help you master alignment logic for triangles and pyramids.
Right alignment is often created by printing “padding” first. Once you can control padding, you can create centered and diamond patterns more easily.
12 people found this page helpful
