Palindromic Number Pyramid in JavaScript

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

What You’ll Learn

Program 56 prints a centered palindromic number pyramid: each row shows 1..i..1 with leading spaces for centering — a natural step after Program 55’s column-wise triangle. This tutorial covers spacing, ascending and descending loops, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Palindromic row

Row i prints 1..i ascending, then i-1..1 descending — always reads the same forward and backward.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) picks the current row and its palindromic width.

Leading Spaces

s = 1..(rows-i)

line += " " repeated rows - i times — centers the pyramid.

Ascending Half

k = 1..i

for (let k = 1; k <= i; k++) line += k + " " — counts up to the peak.

Descending Half

k = i-1..1

for (let k = i - 1; k >= 1; k--) line += k + " " — mirrors without repeating the peak.

O(n²)

Complexity

Row i prints about 2i-1 digits plus spaces — total work grows as O(n²).

Introduction

A palindromic number pyramid prints a centered triangle where row i shows digits from 1 up to i and back down to 1. With rows = 5, you get 1, 1 2 1, 1 2 3 2 1, and so on — each row wider and centered with leading spaces.

In JavaScript use an outer loop for rows, append (rows - i) space pairs to line, then ascending 1..i, then descending i-1..1, before console.log(line.trimEnd()).

Why it matters?

It bridges Program 55’s column-wise fill to centered symmetry — combining spacing with ascending and descending loops on each row.

Key Highlights

Centering

(rows - i) pairs of spaces before digits.

Ascending

k = 1..i prints up to the peak.

vs Program 55

Program 55 uses column-wise 2D array fill; Program 56 logs palindromic rows with spacing.

Series Foundation

Follow Program 55; continue to Program 57 next.

In short: outer i = 1..rows, spaces rows-i, ascending 1..i, descending i-1..1, then console.log(line.trimEnd()).

📝 Problem & Approach

Given row count rows = 5, print a centered palindromic number pyramid — row i shows 1..i..1 with leading spaces.

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

Inputs & Outputs

ItemTypeDescription
rowsintPyramid height — bottom row has rows as peak digit.
i (outer)intCurrent row index — runs 1 to rows.
s (spaces)intAppends (rows - i) pairs of spaces for centering.
k (ascending)intAppends 1..i with trailing space after each digit.
k (descending)intAppends i-1..1 — skips repeating the peak digit.
Row widthintRow i has 2i-1 digits plus leading spaces.

Minimal workflow

Pseudocode
for i from 1 to rows:
    append (rows - i) pairs of spaces to line
    for k from 1 to i:
        append k + " " to line
    for k from i - 1 down to 1:
        append k + " " to line
    console.log(line.trimEnd())

Approach comparison

ApproachIdeaBest for
Three inner loopsSpaces, ascending 1..i, descending i-1..1Learning and interviews
Skip peak in descentk = i-1..1 avoids duplicate peak digitClean palindromic rows
User-input rowsprompt() + parseInt()Flexible pyramid size
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Full diamondMirror bottom half from rows-1..1Extension after mastering pyramid

⚡ Quick Reference

GoalPattern
Outer loopfor (let i = 1; i <= rows; i++)
Leading spacesfor (let s = 0; s < rows - i; s++) line += " "
Ascending halffor (let k = 1; k <= i; k++) line += k + " "
Descending halffor (let k = i - 1; k >= 1; k--) line += k + " "
End rowconsole.log(line.trimEnd())
Program 55 contrastProgram 55 uses column-wise 2D fill; Program 56 uses centered palindromic rows

📋 Fixed Rows vs User Input vs Compact Trace

Same centered 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

Centering
rows - i

Space pairs before digits

Palindrome
1..i..1

Digits per row i

Context

When This Pattern Shows Up

Reach for this pattern when teaching centered output, palindromic sequences, and combining spacing with multiple inner loops.

  1. Post Program 55 exercise

    Natural follow-up after Program 55’s column-wise triangle — introduces centering and palindromic rows.

  2. Palindrome drills

    Each row reads symmetrically — good bridge to string palindrome problems.

  3. Three loops per row

    Spaces plus ascending and descending halves — concrete nested-loop practice.

  4. Gateway to Program 57

    Compare this centered pyramid with the next pattern in the series.

  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 centering, palindromic rows, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the centered palindromic 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 centered palindromic pyramid with five rows — spaces, ascending, and descending loops per row.

Example 1 — Fixed rows = 5

Hard-coded row count — append leading spaces, then ascending 1..i, then descending i-1..1, then log the row.

JavaScript
const rows = 5;

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

  for (let s = 0; s < rows - i; s++) {
    line += "  ";
  }

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

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

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

How It Works

When i = 3, print 2 space pairs, then 1 2 3, then 2 1 — output 1 2 3 2 1. When i = 1, only the ascending loop runs and the descending loop is skipped.

📈 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 s = 0; s < rows - i; s++) {
      line += "  ";
    }

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

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

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

How It Works

Same spacing and palindromic 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 spacing, ascending, and descending loops before scaling to 5 rows.

JavaScript
const rows = 3;

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

  for (let s = 0; s < rows - i; s++) {
    line += "  ";
  }

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

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

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

How It Works

With only three rows you can trace every space pair and digit loop on paper before running the full rows = 5 demo.

🧠 How the Algorithm Prints Rows

1

Set rows

const rows = 5; controls pyramid height and spacing width.

Setup
2

Print leading spaces

for (let s = 0; s < rows - i; s++) line += " " — centers row i.

Spaces
3

Print ascending half

for (let k = 1; k <= i; k++) line += k + " " — counts up to the peak.

Increase
4

Print descending half

for (let k = i - 1; k >= 1; k--) line += k + " " then console.log(line.trimEnd()).

Decrease
=

Palindromic pyramid complete

Row i prints 2i-1 digits — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each row’s space count, ascending half, descending half, and full line output.

iSpace pairsAscendingDescendingRow output
141(skip)1
231 211 2 1
321 2 32 11 2 3 2 1
411 2 3 43 2 11 2 3 4 3 2 1
501 2 3 4 54 3 2 11 2 3 4 5 4 3 2 1

Row i always prints exactly 2i-1 digits — a palindromic line built from spacing plus two inner loops.

Use Cases

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

1. Teaching Nested Loops

Spacing plus ascending and descending loops — three inner loops per row.

Example: trace each row in the walkthrough table — spaces, ascending, descending.

2. Palindrome Drills

Each row reads symmetrically — compare with Program 52's left-aligned palindrome.

Example: row 5 has no leading spaces and shows 1 2 3 4 5 4 3 2 1.

3. Output Formatting Drills

Practice building one line string per row instead of logging inside inner loops.

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

4. Centering Formula

Space pairs on row i = rows - i — fewer spaces as the pyramid widens.

Example: Peak row 10 has 9 space pairs on row 1 — 19 digits on the bottom row.

5. Complexity Intuition

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

Example: Peak row 5 bottom line has 9 digits — 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 is instantly recognizable as a palindrome — spacing, ascending, and descending halves make the shape obvious.

  2. 2. Real Math Connection

    Centering with spaces teaches real console alignment — not abstract loop drill.

  3. 3. Easy to Extend

    Mirror the bottom half from rows-1..1 to build a full diamond, or use fixed-width formatting for larger peaks.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace rows = 3 on paper — row 2 shows 1 2 1 with 1 space pair.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Space pairs = rows - i

    Append (rows - i) pairs of two spaces to line before digits on row i.

  2. 2. Validate User Input

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

  3. 3. Newline After All Inner Loops

    Only call console.log(line.trimEnd()) after all three inner loops finish the row.

  4. 4. Descending starts at i-1

    Loop for (let k = i - 1; k >= 1; k--) so the peak digit is not logged twice.

  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 palindromic number pyramid patterns.

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

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

    → Build line with +=; call console.log(line.trimEnd()) only after all three inner loops.

  2. 2. Wrong Descending Start

    Starting descending at k = i prints the peak digit twice — row looks like 1 2 2 1.

    → Use for (let k = i - 1; k >= 1; k--) — skip the peak in the descending half.

  3. 3. Forgetting Leading Spaces

    Without leading spaces the pyramid is left-aligned, not centered.

    → Print (rows - i) pairs of two spaces before the digits on row i.

  4. 4. Forgetting Newline After Row

    All numbers print on one long line without row breaks.

    → Call console.log(line.trimEnd()) after all 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 descending 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

Bottom row has 9 digits — 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 — total work grows as O(n²).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 55

  • Program 55 fills a 2D array column-wise
  • Program 56 prints centered palindromic rows directly

2. Build a full diamond

  • Print this pyramid, then mirror rows from rows-1 down to 1
  • Compare with Program 54's mirror diagonal diamond

3. Next in series

  • Continue with Program 57
  • Build on centered palindromic patterns

4. Fixed-width formatting

  • Use String(k).padStart(2) when appending digits for rows beyond 9
  • Same loops, better alignment for multi-digit peaks

Notes

  • Three inner loops. Spaces: s = 1..(rows-i). Ascending: k = 1..i. Descending: k = i-1..1.
  • Build one line string per row with += — call console.log(line.trimEnd()) only after all three inner loops finish.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single centered 1.
  • Row i prints 2i-1 digits — total work grows as O(n²) for n rows.

Quick Takeaway: spaces rows-i, ascending 1..i, descending i-1..1, then console.log(line.trimEnd()).

⏱️ 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 palindromic number pyramid is a natural follow-up to Program 55: centered rows built with spacing, ascending, and descending loops. Master the fixed-rows version, then try user input and the compact 3-row trace.

Practice the three examples above, then continue to Program 57 for the next pattern in the series.

Row i prints 2i-1 palindromic digits — centered with (rows-i) space pairs.

💡 Best Practices

✅ Do

  • Spaces: for (let s = 0; s < rows - i; s++) line += " "
  • Ascending: for (let k = 1; k <= i; k++) line += k + " "
  • Descending: for (let k = i - 1; k >= 1; k--) line += k + " "
  • Call console.log(line.trimEnd()) after all three inner loops
  • Use Number.isFinite after parseInt(prompt()) for user input

❌ Don’t

  • Start descending at k = i — duplicates the peak digit
  • Skip leading spaces — pyramid won't be centered
  • 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 palindromic pyramid

Print the centered pyramid the beginner-friendly way.

5
Core concepts
02

Center

rows - i spaces

Code
03

Up

k = 1..i

Code
04

Down

k = i-1..1

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Each row reads the same forward and backward: 1, 1 2 1, 1 2 3 2 1, and so on.
Append (rows - i) groups of two spaces before the numbers on row i — more spaces on upper rows, fewer on lower rows.
A centered pyramid where row i shows 1..i ascending then i-1..1 descending, e.g. row 3: ' 1 2 3 2 1'.
Program 55 fills a 2D array column-wise. Program 56 prints palindromic digits directly with spaces, ascending, and descending loops.
Starting at i-1 avoids printing the peak digit twice — row i already printed i in the ascending loop.
Change rows or read it from user input with prompt() and parseInt — see Example 2.
O(n²) for n rows because each row prints O(n) spaces and digits.
Yes. Print this pyramid for the top half, then mirror rows from rows-1 down to 1 for the bottom half.
Use parseInt with Number.isFinite. Bare parseInt(prompt()) returns NaN on bad input.
One centered row logs a single 1 with (rows-1)*2 = 0 leading spaces.

Did you Know? 🔊

Each row prints 1..i..1 with leading spaces for centering. Row i has 2i-1 digits — total prints grow as O(n²) for n rows.

Continue to Program 57

Move on to the next pattern in the JavaScript number-pattern series.

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