Diagonal Mirror Number Pyramid in JavaScript

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

What You’ll Learn

Program 57 prints a diagonal mirror number pyramid: each row shows the row number twice — once on the left diagonal and once on the right — with spaces everywhere else. A natural step after Program 56’s centered palindromic pyramid. This tutorial covers conditional printing, two inner loops per row, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Mirror diagonals

Row i prints the digit i on the left diagonal and again on the right diagonal — an inverse-V mirror shape.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) picks the current row and the digit to place on both diagonals.

Left Diagonal

j = rows..1

line += (i === j) ? i : " " — scans from the right edge inward.

Right Diagonal

k = 2..rows

line += (i === k) ? i : " " — mirrors the left half from column 2 onward.

Conditional Print

digit or space

Every column position gets either the row digit or a single space — no other characters.

O(n²)

Complexity

Each row scans about 2×rows-1 positions — total work grows as O(n²).

Introduction

A diagonal mirror number pyramid prints the row number on two mirror diagonals with spaces everywhere else. With rows = 5, you get 1, 2 2, 3 3, and so on — forming an inverse-V shape.

In JavaScript use an outer loop for rows, then two inner loops: the first scans j = rows..1 for the left diagonal, the second scans k = 2..rows for the right diagonal, appending the digit only when i === j or i === k.

Why it matters?

It bridges Program 56’s palindromic rows to conditional diagonal placement — combining if checks with two inner loops per row.

Key Highlights

Left diagonal

j = rows..1, append when i === j.

Right diagonal

k = 2..rows, append when i === k.

vs Program 56

Program 56 prints palindromic rows; Program 57 prints the row digit twice on mirror diagonals.

Series Foundation

Follow Program 56; continue to Program 58 next.

In short: outer i = 1..rows, left loop j = rows..1, right loop k = 2..rows, append digit or space, then console.log(line).

📝 Problem & Approach

Given row count rows = 5, print a diagonal mirror number pyramid — row i shows digit i on left and right diagonals with spaces elsewhere.

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

Inputs & Outputs

ItemTypeDescription
rowsintPyramid height — bottom row has rows on both diagonals.
i (outer)intCurrent row index — runs 1 to rows.
j (left)intScans rows..1 — appends digit when i === j.
k (right)intScans 2..rows — appends digit when i === k.
Positions per rowintrows + (rows - 1) = 2×rows - 1 character slots.
Digits per rowintExactly 2 (except row 1 when right loop is empty for rows = 1).

Minimal workflow

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

Approach comparison

ApproachIdeaBest for
Two inner loopsLeft j = rows..1, right k = 2..rowsLearning and interviews
Conditional appendif (i === j) digit else spaceDiagonal placement drills
User-input rowsprompt() + parseInt()Flexible pyramid size
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Character swapReplace digit with * for an X-shapeVisual debugging

⚡ Quick Reference

GoalPattern
Outer loopfor (let i = 1; i <= rows; i++)
Left diagonalfor (let j = rows; j >= 1; j--) line += (i === j) ? i : " "
Right diagonalfor (let k = 2; k <= rows; k++) line += (i === k) ? i : " "
End rowconsole.log(line)
Program 56 contrastProgram 56 uses palindromic rows; Program 57 uses mirror diagonals

📋 Fixed Rows vs User Input vs Compact Trace

Same diagonal mirror pyramid — 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 half
j = rows..1

Append when i === j

Right half
k = 2..rows

Append when i === k

Context

When This Pattern Shows Up

Reach for this pattern when teaching conditional printing, diagonal placement, and combining two inner loops per row.

  1. Post Program 56 exercise

    Natural follow-up after Program 56’s palindromic pyramid — introduces conditional diagonal placement.

  2. Diagonal drills

    Each row places digits on mirror diagonals — good bridge to matrix diagonal problems.

  3. Two loops per row

    Left and right halves with if checks — concrete nested-loop practice.

  4. Gateway to Program 58

    Program 58 extends this diagonal logic to a full diamond — compare after mastering this pyramid.

  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 conditional printing, mirror diagonals, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the centered diagonal mirror number pyramid 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 a diagonal mirror pyramid with five rows — left and right inner loops with conditional printing per row.

Example 1 — Fixed rows = 5

Hard-coded row count — scan left diagonal j = rows..1, then right diagonal k = 2..rows, appending digit or space.

JavaScript
const rows = 5;

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

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

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

  console.log(line);
}
Try it Yourself

How It Works

When i = 3, the left loop prints spaces then 3 at j = 3; the right loop prints spaces then 3 at k = 3 — output 3 3. When i = 1, only the left loop places a digit; the right loop is all spaces.

📈 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 = rows; j >= 1; j--) {
      line += (i === j) ? i : " ";
    }

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

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

How It Works

Same conditional diagonal logic 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 loops before scaling to 5 rows.

JavaScript
const rows = 3;

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

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

  for (let k = 2; k <= rows; 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 pyramid height and the maximum digit printed.

Setup
2

Scan left diagonal

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

Left half
3

Scan right diagonal

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

Right half
4

End the row

Call console.log(line) after both inner loops finish — one mirror-diagonal row complete.

Newline
=

Diagonal mirror pyramid complete

Each row scans 2×rows-1 positions — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

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

iLeft hit (j)Right hit (k)Row output
1j = 1(none)1
2j = 2k = 22 2
3j = 3k = 33 3
4j = 4k = 44 4
5j = 5k = 55 5

Row i always prints exactly two digits (one per diagonal) when rows > 1 — spaced across 2×rows-1 character positions.

Use Cases

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

1. Teaching Nested Loops

Two inner loops with conditional printing — classic diagonal placement drill.

Example: trace each row in the walkthrough table — left hit, right hit.

2. Diagonal Drills

Each row mirrors digits on two diagonals — compare with Program 53’s single diagonal V-shape.

Example: row 5 prints 5 at column 5 and again at column 9.

3. Output Formatting Drills

Practice building one line string per row with digit-or-space decisions per column.

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

4. Why k starts at 2

Starting the right loop at 2 avoids a third digit at the center — keeps exactly two prints per row.

Example: try k = 1 and see the center digit triple on some rows.

5. Complexity Intuition

Each row scans about 2n positions — makes O(n²) concrete for beginners.

Example: row 5 with rows = 5 scans 9 character slots — see the walkthrough table.

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row validation 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

    Each row instantly forms an inverse-V — two digits on mirror diagonals make the shape obvious.

  2. 2. Real Math Connection

    Conditional digit-or-space printing teaches real console alignment — not abstract loop drill.

  3. 3. Easy to Extend

    Swap digits for * to get an X-shape, or extend to Program 58’s full diamond.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace rows = 3 on paper — row 2 shows 2 2 with one space between the digits.

Usage Tips

Small habits that keep number-pattern code clean.

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

    Append the digit when i === j; otherwise append a single space.

  2. 2. Validate User Input

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

  3. 3. Newline After Both Inner Loops

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

  4. 4. Right loop starts at k = 2

    Use for (let k = 2; k <= rows; k++) so the center position is not duplicated.

  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 called console.log() inside the inner loop.

Common Pitfalls

Mistakes that commonly break diagonal mirror number pyramid patterns.

  1. 1. console.log() Inside Inner Loop

    Each digit lands on its own line — you get a column, not a pyramid.

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

  2. 2. Right Loop Starts at 1

    Starting at k = 1 can print a third digit at the center — row looks crowded.

    → Use for (let k = 2; k <= rows; k++) — mirror from column 2 onward.

  3. 3. Wrong Condition Check

    Using j === rows instead of i === j places digits on the wrong diagonal.

    → Always compare the outer row index i with the inner loop variable j or k.

  4. 4. Forgetting Newline After Row

    All numbers print on one long line without row breaks.

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

  5. 5. Unchecked parseInt(prompt())

    Letters or empty input yield NaN or leave rows invalid.

    → Validate with Number.isFinite(rows) and check rows >= 1 before drawing.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 — the right loop (k = 2..1) 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

Bottom row has two copies of 5 across 9 positions — good for dry-runs before scaling up.

Bad input

Non-numeric input

Bare parseInt(prompt()) returns NaN — validate with Number.isFinite.

Large rows

Wide output

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

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 56

  • Program 56 prints centered palindromic rows (1..i..1)
  • Program 57 prints the row digit twice on mirror diagonals

2. Build Program 58 diamond

  • Print this pyramid, then add the inverted bottom half
  • Compare with Program 58’s full diagonal mirror diamond

3. Next in series

  • Continue with Program 58
  • Extend diagonal logic to a full diamond shape

4. Character swap

  • Replace (i === j) ? i : " " with "*" in both diagonal branches
  • Same loops, clean X-shape for visual debugging

Notes

  • Two inner loops. Left: j = rows..1, append when i === j. Right: k = 2..rows, append when i === k.
  • Build one line string per row with += — call console.log(line) only after both inner loops finish.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1 on the left diagonal.
  • Row i scans 2×rows-1 positions — total work grows as O(n²) for n rows.

Quick Takeaway: left j = rows..1, right k = 2..rows, digit or space, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Digits on row i2i - 1No storage beyond loop counters
Wrap Up

🎉 Conclusion

The diagonal mirror number pyramid is a natural follow-up to Program 56: each row places the row digit on two mirror diagonals with conditional printing. Master the fixed-rows version, then try user input and the compact 3-row trace.

Practice the three examples above, then continue to Program 58 for the full diagonal mirror diamond.

Row i prints two copies of digit i — one on each mirror diagonal across 2×rows-1 positions.

💡 Best Practices

✅ Do

  • Left: for (let j = rows; j >= 1; j--) with if (i === j)
  • Right: for (let k = 2; k <= rows; k++) with if (i === k)
  • Append a single space for non-matching positions
  • Call console.log(line) after both inner loops
  • Use Number.isFinite after parseInt(prompt()) for user input

❌ Don’t

  • Start right loop at k = 1 — can triple-print at center
  • Use j === rows instead of i === j — wrong diagonal
  • Call console.log() inside any inner loop
  • Ignore bad console 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 diagonal mirror pyramid

Print the mirror-diagonal pyramid the beginner-friendly way.

5
Core concepts
02

Left

j = rows..1

Code
03

Right

k = 2..rows

Code
04

Check

i === j or i === k

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The left inner loop places the row number on the left diagonal; the right inner loop mirrors it on the right diagonal.
Starting at k = 2 avoids duplicating the center position — each row prints the number at most twice.
Row i shows the digit i on two diagonals with spaces between, e.g. row 3 with rows = 5: ' 3 3'.
Program 56 prints a centered palindromic row (1..i..1). Program 57 prints only the row number twice on mirror diagonals.
Each column position gets either the row digit or a space — the conditions pick exactly two print positions per row.
Change rows or read it from user input with prompt() and parseInt — see Example 2.
O(n²) for n rows because each row scans about 2n character positions.
Yes. Replace the digit with '*' in both diagonal append branches.
Use parseInt with Number.isFinite. Bare parseInt(prompt()) returns NaN on bad input.
One row logs a single 1 — the right loop (k = 2..1) does not run.

Did you Know? 🔊

Each row prints the row number twice — once on the left diagonal and once on the right — with spaces everywhere else. Total positions per row = 2×rows-1.

Continue to Program 58

Move on to the full diagonal mirror diamond in the JavaScript number-pattern series.

Program 58 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