JavaScript Binary Rows Pattern (Alternating 1 and 0)
Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview
Definition
What Is This Pattern?
An alternating 1/0 triangle prints a shrinking row of the same digit each time — odd rows are all 1s, even rows are all 0s — chosen with i % 2.
Remember
Rule: for i = 1..rows
print (i % 2) repeated (rows - i + 1) times
11111
0000
111
00
1 ← rows = 5
After Program 39’s rotating digits, this pattern focuses on parity and a shrinking inner bound.
Approach
How to Solve It
Walk i from 1 to rows; repeat i % 2 from j = i to rows.
Method
Idea
Best for
Parity + shrink
Digit = i % 2; inner j = i..rows
Learning, interviews
prompt rows
Same loops; read rows at runtime
Interactive practice
Spaced digits
Same bounds; line += (i % 2) + " "
Readable console output
Pseudocode
Pseudocode
for i from 1 to rows:
line = ""
for j from i to rows:
line += (i mod 2)
print line
Cheat sheet
Goal
Pattern
Set rows
const rows = 5;
Outer loop
for (let i = 1; i <= rows; i++)
Inner loop
for (let j = i; j <= rows; j++)
Row digit
line += i % 2;
End row
console.log(line);
Chars per row
rows - i + 1
Flip parity
line += 1 - (i % 2);
Printing Numbers vs Starting a New Line
API
Effect
Use for
line += i % 2
Stays on the same row
Each digit
console.log(line)
Ends the line
After the inner loop
Build the row with +=, then break once with console.log. Putting console.log inside the inner loop prints one digit per line.
Try it
Live Preview
Change the row count and the alternating triangle updates instantly.
Whole numbers from 1 to 9. Tap a chip or type a value — the preview redraws as you go.
Live resultrows = 5 · digits = 15
11111
0000
111
00
1
Trace
Worked Walkthrough — rows = 3
Trace each outer i, the parity digit, how many times it repeats, and the printed row.
i
i % 2
Repeats
Printed row
1
1
3
111
2
0
2
00
3
1
1
1
Repeats = rows - i + 1. Total digits = 6 = 3×4/2.
Code
JavaScript Programs
Three complete programs: fixed rows = 5, prompt rows, and spaced digits. Use View Output for sample results, or Try It Yourself to edit and run in the playground.
Example 1 — Fixed rows = 5
Hard-coded height — shrink the inner loop and append i % 2 each time.
JavaScript
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = i; j <= rows; j++) {
line += i % 2;
}
console.log(line);
}
1. Outer loop.i is both the row index and the parity source via i % 2.
2. Inner loop.j runs from i to rows, so the row shortens by one each time.
3. Digit. Odd i appends 1; even i appends 0. Then console.log(line).
Example 2 — prompt Rows
Read rows at runtime with prompt and parseInt.
JavaScript
const rows = parseInt(prompt("Enter rows:"), 10);
if (!Number.isFinite(rows) || rows < 1) {
console.log("Please enter a positive integer.");
} else {
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = i; j <= rows; j++) {
line += i % 2;
}
console.log(line);
}
}