Alternating 0-1 Triangle in JavaScript

What You’ll Learn
How to print an alternating 0-1 triangle in JavaScript using nested loops and modulo arithmetic.
This pattern helps you understand how parity (% 2) can be used to generate binary-like sequences.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
01
101
0101
10101Complete JavaScript Program
Outer loop grows row size. Inner loop moves backward and prints j % 2, creating alternating 0/1 digits.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = i; j >= 1; j--) {
line += j % 2;
}
console.log(line);
}🧠 How It Works
Set number of rows
const rows = 5; controls triangle height.
Outer loop grows row width
for (let i = 1; i <= rows; i++) increases row length from 1 to 5.
Inner loop + modulo
for (let j = i; j >= 1; j--) runs backward, and j % 2 outputs alternating bits.
Print each row
console.log(line); outputs one generated row per iteration.
Alternating 0-1 triangle
Modulo arithmetic provides a compact way to convert counting loops into alternating digit patterns.
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 = 1; i <= rows; i++) {
for (let j = i; j >= 1; j--) {
document.write(j % 2);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Use user input to set dynamic row count
- Start inner loop from 1 for a mirrored bit pattern
- Replace 0/1 with symbols like
*and- - Store rows in an array and render them into the DOM
- Add spacing between bits for easier visual parsing
Avoid
- Using wrong loop direction when you expect `01` or `10` starts
- Mixing row index and column index parity accidentally
- Skipping validation for negative row values
- Using
document.writein production frontends
Key Takeaways
The outer loop controls triangle height and row width.
The inner loop builds each row by iterating backward.
j % 2 is the core trick for alternating 0 and 1 values.
Small loop-direction changes create different binary-style patterns.
❓ Frequently Asked Questions
j = i down to 1, so for i = 2, values are 2 then 1, producing 0 then 1.1 and flip it each column.document.write to render directly in an HTML page.Explore More JavaScript Number Patterns!
Use loop direction and modulo together to create richer, logic-driven pattern outputs.
Many binary pattern problems can be solved with just one expression: value % 2. It is one of the simplest parity tools in programming.
12 people found this page helpful
