Alternating Odd-Even Row Pattern in JavaScript

What You’ll Learn
How to print an alternating odd-even row pattern where odd rows contain odd sequences and even rows contain even sequences.
This is a practical nested-loop example with a row-level parity condition.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 4
1 3 5
2 4 6 8
1 3 5 7 9Complete JavaScript Program
Set start value based on row parity, then print that parity sequence with +2 increments.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
let k = i % 2 === 0 ? 2 : 1;
for (let j = 1; j <= i; j++) {
line += k + (j < i ? " " : "");
k += 2;
}
console.log(line);
}🧠 How It Works
Choose row count
const rows = 5; sets triangle height.
Outer loop controls row index
for (let i = 1; i <= rows; i++) moves row-by-row from 1 to 5.
Parity decides start value
k = i % 2 === 0 ? 2 : 1 selects even or odd sequence for that row.
Inner loop prints row terms
Each iteration appends k and then updates k += 2, preserving parity within the row.
Alternating odd/even rows
One condition plus a +2 update is enough to switch between odd and even sequences cleanly.
Variation — Browser (document.write) Version
Print the same pattern directly in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
for (let i = 1; i <= 5; i++) {
let k = i % 2 === 0 ? 2 : 1;
for (let j = 1; j <= i; j++) {
document.write(k + " ");
k += 2;
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Accept row count input for dynamic sequence depth
- Swap start values to invert odd/even row behavior
- Use commas or tabs instead of spaces between numbers
- Create centered output by padding each row
- Render output using DOM elements instead of
document.write
Avoid
- Forgetting to reinitialize
kfor each row - Incrementing
kby 1 when parity should stay fixed - Using incorrect row conditions for odd/even checks
- Using
document.writein production-grade apps
Key Takeaways
The outer loop sets row number and row width.
A parity condition picks odd or even starting value.
Using k += 2 keeps all row values in same parity class.
Conditional row patterns are built by combining loops and simple state.
❓ Frequently Asked Questions
i = 2 is even, so start value is k = 2, then it increments by 2 to print 2 4.k = 2 and even rows use k = 1.document.write for browser output.Explore More JavaScript Number Patterns!
Use parity checks and loop updates together to build rich mixed-sequence patterns.
Patterns that alternate odd and even rows are an excellent way to practice state initialization per row.
12 people found this page helpful
