Mirror Diagonal Number Pattern in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Conditions

What You’ll Learn

Program 53 prints a mirror diagonal number pattern: each row shows the row number on the main diagonal (left) and on a mirrored diagonal (right), forming a symmetric V-shape — a natural step after Program 52’s palindromic pyramid. This tutorial covers two inner loops with i === j and i === k conditions, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Mirrored diagonals

Row i logs i on the main diagonal and again on the mirrored diagonal — spaces fill every other column.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) picks the current row index.

Left Half

j = 1..rows

line += (i === j ? i : " ") — append the digit only on the main diagonal.

Right Half

k = rows-1..1

line += (i === k ? i : " ") — mirrored diagonal; skipping the center column avoids duplication.

Live Preview

rows = 3..9

Pick row count and draw the V-shaped mirror diagonal pattern in the browser.

O(n²)

Complexity

Each row logs about 2n-1 characters — total work grows as O(n²).

Introduction

A mirror diagonal number pattern prints row i with the digit i on the main diagonal and again on a mirrored diagonal — spaces fill the gaps to form a V-shape. With rows = 5, you get 1 1, 2 2, 3 3, 4 4, 5.

In JavaScript, use an outer loop for rows, then two inner loops: left half with i === j, right mirrored half with i === k, appending spaces elsewhere before console.log(line).

Why it matters?

It bridges Program 52’s palindromic rows to conditional diagonal placement — combining nested loops with i === j logic.

Key Highlights

Left diagonal

i === j logs the row digit on the main diagonal.

Right diagonal

i === k mirrors the digit on the opposite diagonal.

vs Program 52

Program 52 uses m++/m-- for palindromic rows; Program 53 uses spacing and conditions.

Series Foundation

Follow Program 52; continue to Program 54 next.

In short: outer for (let i = 1; i <= rows; i++), left loop for (let j = 1; j <= rows; j++) with i === j, right loop for (let k = rows - 1; k >= 1; k--) with i === k, else space, then console.log(line).

📝 Problem & Approach

Given row count rows = 5, print a mirror diagonal number pattern — row i shows digit i on both diagonals with spaces between.

JavaScript
// rows = 5
// 1       1
//  2     2
//   3   3
//    4 4
//     5

Inputs & Outputs

ItemTypeDescription
rowsnumberHow many V-shaped rows to log.
i (outer)numberCurrent row index — runs from 1 to rows.
j (left)numberScans columns 1..rows; appends digit when i === j.
k (right)numberScans columns rows-1..1; appends digit when i === k.
Cell outputstringDigit when condition matches; otherwise a space.
Row widthnumberAbout 2n-1 characters per row.

Minimal workflow

Pseudocode
for i from 1 to rows:
    line = ""
    for j from 1 to rows:
        append digit if i === j else space
    for k from rows - 1 down to 1:
        append digit if i === k else space
    console.log(line)

Approach comparison

ApproachIdeaBest for
Two inner loopsLeft i === j, right i === k with spaces elsewhereLearning and interviews
Ternary operatori === j ? i : " "Compact one-liners
User-input rowsparseInt(prompt())Flexible row count
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Full X patterni === j || i + j === rows + 1 in one loopExtension after mastering V-shape

⚡ Quick Reference

GoalPattern
Outer loopfor (let i = 1; i <= rows; i++)
Left halffor (let j = 1; j <= rows; j++) line += (i === j ? i : " ");
Right halffor (let k = rows - 1; k >= 1; k--) line += (i === k ? i : " ");
End rowconsole.log(line);
Skip center duplicateRight loop starts at rows - 1, not rows
Program 52 contrastProgram 52 uses palindromic m++/m--; Program 53 uses diagonal conditions

📋 Fixed Rows vs User Input vs Compact Trace

Same V-shape — three ways to set row count and trace the logic.

Fixed rows
rows = 5

Hard-coded height for demos

User input
parseInt(prompt())

Read row count from console

Compact trace
rows = 3

Quick dry-run on paper

Left diagonal
i === j

Main diagonal digit placement

Right diagonal
i === k

Mirrored diagonal digit placement

Context

When This Pattern Shows Up

Reach for this pattern when teaching conditional diagonal placement, mirrored halves, and spacing in console output.

  1. Post Program 52 exercise

    Natural follow-up after Program 52’s palindromic pyramid — introduces i === j diagonal conditions.

  2. Diagonal drills

    Each row places digits only where indices match — good bridge to matrix and grid problems.

  3. Two halves per row

    Each row scans about 2n-1 positions — classic nested-loop O(n²) complexity.

  4. Gateway to Program 54

    Program 54 mirrors this V-shape downward to form a full diamond — compare the two next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in diagonal conditions, mirrored halves, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the mirror diagonal number pattern in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed rows, user input, and a compact trace demo. Click View Output to reveal sample console results, or Try it Yourself to run in the browser.

📚 Getting Started

Print five rows of the mirror diagonal V-shape with conditional digit placement on both diagonals.

Example 1 — Fixed rows = 5

Hard-coded row count — append digit when i === j or i === k, otherwise append a space.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";

  for (let j = 1; j <= rows; j++) {
    line += (i === j ? i : " ");
  }

  for (let k = rows - 1; k >= 1; k--) {
    line += (i === k ? i : " ");
  }

  console.log(line);
}
Try it Yourself

How It Works

When i = 3, the left loop appends spaces until j = 3, then the right loop appends spaces until k = 3 — output 3 3. When i = 5, only the center column gets a digit because both diagonals meet at the bottom tip.

📈 User Input

Read row count with prompt() and Number.isFinite validation.

Example 2 — User Input Rows

Read rows with prompt() and validate the result.

JavaScript
const rowsInput = prompt("Enter the number of rows:");
const rows = parseInt(rowsInput, 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 = 1; j <= rows; j++) {
      line += (i === j ? i : " ");
    }

    for (let k = rows - 1; k >= 1; k--) {
      line += (i === k ? i : " ");
    }

    console.log(line);
  }
}
Try it Yourself

How It Works

Same diagonal two-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Compact Trace

Smaller row count for quick tracing on paper or in interviews.

Example 3 — Compact rows = 3

Use rows = 3 to trace left and right diagonal conditions before scaling to 5 rows.

JavaScript
const rows = 3;

for (let i = 1; i <= rows; i++) {
  let line = "";

  for (let j = 1; j <= rows; j++) {
    line += (i === j ? i : " ");
  }

  for (let k = rows - 1; k >= 1; k--) {
    line += (i === k ? i : " ");
  }

  console.log(line);
}
Try it Yourself

How It Works

With only three rows you can trace every i === j and i === k check on paper before running the full rows = 5 demo.

🧠 How the Algorithm Prints Rows

1

Set rows

const rows = 5; controls how many V-shaped lines log.

Setup
2

Scan left half

for (let j = 1; j <= rows; j++) — append digit when i === j, else space.

Left
3

Scan right half

for (let k = rows - 1; k >= 1; k--) — append digit when i === k, else space.

Right
4

End the row

console.log(line) after both inner loops finish the current line.

Newline
=

Mirror diagonal V complete

Each row prints about 2n-1 characters — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each row’s left diagonal position, right diagonal position, and full line output.

iLeft (j)Right (k)Row output
1j = 1k = 11 1
2j = 2k = 22 2
3j = 3k = 33 3
4j = 4k = 44 4
5j = 5(none — center tip)5

Row 5 prints only one digit because the right loop starts at rows - 1, avoiding a duplicate center column.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Each row scans a fixed-width grid with conditional digit placement.

Example: trace row i = 3 in the walkthrough table.

2. Diagonal Drills

Each row mirrors digits on two diagonals — good bridge to matrix indexing.

Example: row 5 ends with a single center digit 5 at the V tip.

3. Output Formatting Drills

Practice line += (i === j ? i : " ") vs console.log(line) with two inner loops per row.

Example: put console.log(line) inside the inner loop by mistake.

4. Grid Scanning

Each row prints about 2n-1 characters — links loops to grid traversal.

Example: 10 rows scan about 19 characters on the widest line.

5. Complexity Intuition

Growing inner bound makes O(n²) concrete — count prints for n rows.

Example: 5 rows scan about 9 characters per line on average.

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row checks after parseInt(prompt()).

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong conditions show up immediately as misaligned diagonals.

  2. 2. Real Math Connection

    Each row uses real diagonal logic — not abstract loop drill.

  3. 3. Easy to Extend

    Change rows, use fixed-width format, or switch to full rectangular table.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace row i = 3 on paper — watch both loops print 3 at column 3 with spaces elsewhere.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Left loop j = 1..rows

    Scan all columns in the left half — append digit only when i === j.

  2. 2. Validate with Number.isFinite

    Avoid crashes when the user types letters instead of a number.

  3. 3. console.log After Inner Loop

    Only call console.log(line) after both inner loops finish the row.

  4. 4. Right loop k = rows-1..1

    Start the right loop at rows - 1 to skip duplicating the center column.

  5. 5. Dry-Run rows = 5

    Trace five rows on paper before coding the full 10-row demo.

Pro Tip: if the output is a vertical list of single numbers, you almost certainly put console.log(line) inside the inner loop.

Common Pitfalls

Mistakes that commonly break mirror diagonal number patterns.

  1. 1. console.log Inside Inner Loop

    Each character lands on its own line — you get a column, not a V-shape.

    → Use line += (i === j ? i : " ") in both loops; console.log(line) only after both inner loops.

  2. 2. Wrong Right Loop Start

    Starting the right loop at k = rows duplicates the center digit on the bottom row.

    → Use for (let k = rows - 1; k >= 1; k--) — skip the center column.

  3. 3. Using i !== j Instead of i === j

    Digits appear everywhere instead of on the diagonals only.

    → Append the digit when i === j (or i === k), not when they differ.

  4. 4. Forgetting console.log After Row

    All numbers log on one long line without row breaks.

    → Add console.log(line) after both inner loops complete.

  5. 5. Blind parseInt(prompt())

    Letters or empty input return NaN when parseInt(prompt()) is unchecked.

    → Validate with Number.isFinite(rows) and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 — the right loop does not run.

rows = 0

Empty output

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 5

Compact trace

Five rows ending with a single center 5 — good for dry-runs.

Bad input

Non-numeric input

Unchecked parseInt(prompt()) returns NaN — use Number.isFinite.

Large rows

Wide output

Row 9 scans 17 character positions — total work grows as O(n²).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 52

  • Program 52 uses palindromic m++/m-- rows
  • Program 53 uses spacing and i === j diagonal conditions

2. Change rows

  • Try rows = 4 or rows = 7 in the live preview
  • Same diagonal logic, different V height

3. Next in series

  • Continue with Program 54
  • Mirror this V-shape downward to form a diamond

4. Print a full X

  • Use i === j || i + j === rows + 1 in one column loop
  • Same conditions, both diagonals in a single scan

Notes

  • Two inner loops. Left: j = 1..rows with i === j. Right: k = rows-1..1 with i === k. Else append a space.
  • line += ... builds the row; console.log(line) advances — call it only after both inner loops finish.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1.
  • Each row prints about 2n-1 characters — total work is O(n²) for n rows.

Quick Takeaway: outer for (let i = 1; i <= rows; i++), left i === j, right i === k, else space, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Characters per rowAbout 2n-1No storage beyond loop counters
Wrap Up

🎉 Conclusion

The mirror diagonal number pattern is a natural follow-up to Program 52: conditional digit placement on mirrored diagonals with spaces elsewhere. Master the fixed-rows version, then try user input and the compact 3-row trace.

Practice the three examples above, then continue to Program 54 to mirror this V-shape into a full diamond.

Row i logs digit i on both diagonals — left with i === j, right with i === k.

💡 Best Practices

✅ Do

  • Left loop: for (let j = 1; j <= rows; j++) line += (i === j ? i : " ");
  • Right loop: for (let k = rows - 1; k >= 1; k--) line += (i === k ? i : " ");
  • Start the right loop at rows - 1 to skip center duplication
  • Call console.log(line) after both inner loops
  • Use Number.isFinite for user input

❌ Don’t

  • Start right loop at k = rows — duplicates the center digit
  • Append digits when i !== j — fills the whole row with numbers
  • Call console.log(line) inside either inner loop
  • Ignore bad input in user-facing demos
  • Skip the rows = 3 dry-run before coding rows = 5

Key Takeaways

Knowledge Unlocked

Five things to remember about this mirror diagonal pattern

Print the V-shape the beginner-friendly way.

5
Core concepts
02

Left

i === j

Code
03

Right

i === k

Code
04

Skip center

k = rows - 1..1

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The mirrored half logs rows-1 positions to avoid duplicating the center column. On the final row, only the main diagonal digit remains.
It logs the row number on the main diagonal (left) and on a mirrored diagonal (right), creating a symmetric V-shape like 1..5 on both sides.
The first loop appends the left half across rows columns. The second appends the right mirrored half across rows-1 columns in reverse.
Skipping the center column prevents logging the middle digit twice on rows where i equals the center index.
Change rows or read it from user input with parseInt(prompt()) — see Example 2.
O(n²) for n rows because each row logs about 2n-1 characters using nested loops.
Program 52 builds palindromic digit rows with increment/decrement counters. Program 53 uses spacing and i === j / i === k to place digits on mirrored diagonals.
Yes. Append when i === j or i + j === rows + 1 in a single column loop.
Use parseInt with Number.isFinite. Bare parseInt(prompt()) returns NaN on bad input.
One row logs a single 1 — the left loop appends at j = 1 and the right loop does not run.

Did you Know? 🔊

Each row logs the row number on the main diagonal (left) and on a mirrored diagonal (right) using i === j and i === k. Row 3 shows 3 on both sides — about 2n-1 characters per row, so O(n²) total.

Continue to Program 54

Mirror this V-shape downward to form a full diamond in the next tutorial.

Program 54 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful