Alternating Ascending/Descending Number Triangle in JavaScript

What You’ll Learn
How to print an alternating direction number triangle where odd rows go ascending and even rows go descending.
This pattern combines loop control with if conditions based on odd/even row values.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
4321
123
21
1Complete JavaScript Program
Outer loop goes from rows down to 1. Even rows print descending order; odd rows print ascending order.
const rows = 5;
for (let i = rows; i >= 1; i--) {
let line = "";
if (i % 2 === 0) {
for (let j = i; j >= 1; j--) {
line += j;
}
} else {
for (let j = 1; j <= i; j++) {
line += j;
}
}
console.log(line);
}🧠 How It Works
Set row count
const rows = 5; defines the first row length and number of rows.
Outer loop (descending rows)
for (let i = rows; i >= 1; i--) controls row length from 5 down to 1.
Parity check decides direction
if (i % 2 === 0) chooses descending loop (i..1) for even rows; odd rows use ascending loop (1..i).
Print each generated row
console.log(line); outputs the row and moves to the next line.
Alternating number triangle
Direction flips row by row based on parity, while total printed digits still follow triangular growth (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--) {
if (i % 2 === 0) {
for (let j = i; j >= 1; j--) {
document.write(j);
}
} else {
for (let j = 1; j <= i; j++) {
document.write(j);
}
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Let users choose row count and starting direction
- Swap odd/even rules to create a mirrored variation
- Add spaces between numbers for cleaner readability
- Use arrays and
join("")to build each row more flexibly - Render output in a
<pre>element via DOM APIs
Avoid
- Forgetting the odd/even condition before printing each row
- Mixing row length logic between outer and inner loops
- Using invalid inputs without validating row count
- Using
document.writein production interfaces
Key Takeaways
The outer loop sets the row length from rows down to 1.
An odd/even condition switches print direction for each row.
Even rows print descending, odd rows print ascending in this version.
Conditional nested loops can create rich mixed-direction patterns.
❓ Frequently Asked Questions
i = 4 is even, so the descending loop runs from 4 down to 1.if and else sections.document.write to render row by row in HTML.Explore More JavaScript Number Patterns!
Practice conditional patterns to improve your nested-loop and branching skills together.
Alternating direction patterns are a great way to combine two core topics: loops and conditionals. A single if can completely change row behavior.
12 people found this page helpful
