Palindrome Number Triangle in JavaScript

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

What You’ll Learn

The palindrome number triangle appends 1, then 212, then 32123, … — a natural follow-up after Program 36’s right-aligned decreasing triangle. This tutorial covers descending and ascending inner loops, row symmetry, nested loops, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Palindrome row

Row i appends i down to 2, then 1 up to i — a symmetric sequence.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) — one palindrome row per iteration.

Left Half

i..2

for (let j = i; j >= 2; j--) — appends the descending left side of the palindrome.

Right Half

1..i

for (let j = 1; j <= i; j++) — completes the palindrome with ascending digits.

Live Preview

3–7 rows

Pick a row count and draw the palindrome number triangle in the browser.

O(n²)

Complexity

Digits per row = 2i - 1 — total digits = .

Introduction

A palindrome number triangle prints a symmetric sequence on each row: 1, then 212, then 32123, and so on. With rows = 5, each row reads the same forward and backward.

In JavaScript you use two inner loops per row: append j from i down to 2, then from 1 up to i, then console.log(line).

Why it matters?

It combines descending and ascending inner loops to build symmetry — a step after Program 36’s right-aligned decreasing pattern.

Key Highlights

i..2 desc

Left half.

1..i asc

Right half.

2i - 1

Digits per row.

Series Foundation

Follow Program 36; continue to Program 38 next.

In short: outer i = 1..rows, desc j = i..2, asc j = 1..i, then console.log(line).

📝 Problem & Approach

Given rows = 5, print a palindrome number triangle: for each row i, append descending i..2 then ascending 1..i.

JavaScript
# rows = 5
# 1
# 212
# 32123
# 4321234
# 543212345

Inputs & Outputs

ItemTypeDescription
rowsintTriangle height — number of palindrome lines to print.
iintOuter loop — current row (1 to rows).
jintInner loop — descending (i..2) or ascending (1..i).

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from i down to 2: print j
    for j from 1 to i: print j
    console.log(line)

Approach comparison

ApproachIdeaBest for
Fixed rows1, 212, …Learning and interviews
User-input rowsparseInt(prompt(...), 10)Configurable triangle size
Compact tracerows = 3 on paper firstDebugging loop bounds

⚡ Quick Reference

GoalPattern
Outer loopfor (let i = 1; i <= rows; i++)
Left half (desc)for (let j = i; j >= 2; j--) line += j
Right half (asc)for (let j = 1; j <= i; j++) line += j
End the rowconsole.log(line)
User inputparseInt(prompt(...), 10)

📋 Fixed vs User Input vs Compact Demo

Same palindrome triangle — different ways to control the row count.

Outer loop
i = 1..rows

One palindrome row per iteration

Left half
j = i..2

Descending digits

Right half
j = 1..i

Ascending digits

Learning tip
2i - 1

Digits per row

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetry, dual inner loops, and palindrome construction in nested loops.

  1. After Program 36

    Natural follow-up — replaces right alignment with symmetric palindrome rows built from two inner loops.

  2. Symmetry drills

    Practice descending then ascending loops to build mirrored sequences on each row.

  3. Console I/O practice

    Combine loops with prompt() and Number.isFinite for flexible row counts.

  4. Gateway to variants

    Compare Program 36 (decreasing) and Program 38 (next in series) 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 dual inner loops, formatted output, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 7 and draw the palindrome number triangle in the browser.

Try 3, 5, or 7. Rows between 3 and 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

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

📚 Getting Started

Print five rows of the palindrome number triangle with descending and ascending inner loops.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = i; j >= 2; j--) {
    line += j;
  }
  for (let j = 1; j <= i; j++) {
    line += j;
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 3, the first loop appends 3 2, the second appends 1 2 3 — output 32123. When i = 1, only the ascending loop runs — output 1.

📈 User Input

Read the row count with prompt() and parseInt() instead of hard-coding 5.

Example 2 — User input rows

Read rows with prompt() and parseInt() instead of hard-coding 5.

JavaScript
const rowsInput = prompt("Enter 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 = i; j >= 2; j--) {
      line += j;
    }
    for (let j = 1; j <= i; j++) {
      line += j;
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same palindrome core as Example 1; only rows comes from user input instead of being hard-coded as 5. Non-numeric input yields NaN with bare parseInt(prompt(), 10) — validate with Number.isFinite for safer labs.

⚡ Smaller Demo

Run with rows = 3 to trace every row on paper before scaling up.

Example 3 — Compact rows = 3

Same descending and ascending loops with a smaller row count for quick tracing.

JavaScript
const rows = 3;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = i; j >= 2; j--) {
    line += j;
  }
  for (let j = 1; j <= i; j++) {
    line += j;
  }
  console.log(line);
}
Try it Yourself

How It Works

Only rows changes from 5 to 3 — the two inner loops stay identical. Trace i = 1, 2, 3 on paper to see how each row grows symmetrically.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed for fixed rows; use prompt() when reading. Set loop variables i, j with rows = 5.

Setup
2

Outer loop walks rows

for (let i = 1; i <= rows; i++) — ascending outer loop; one palindrome row per iteration.

Row
3

Left half (descending)

for (let j = i; j >= 2; j--) — appends i, i-1, ..., 2.

Mirror left
4

Right half (ascending)

for (let j = 1; j <= i; j++) — completes the palindrome: 1, 2, ..., i.

Mirror right
5

New line

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

Break
=

Palindrome triangle complete

Digits per row = 2i - 1 — total digits = ; O(n²) time.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, left and right halves, and full row output.

iLeft half (i..2)Right half (1..i)Row output
111
221, 2212
33, 21, 2, 332123
44, 3, 21, 2, 3, 44321234
55, 4, 3, 21, 2, 3, 4, 5543212345

Digits per row = 2i - 1 — total digits = 1 + 3 + 5 + ... + (2n-1) = n².

Use Cases

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

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: swap the ascending and descending loops and watch the palindrome break.

2. Pattern Series Base

Foundation for symmetry-based patterns and mirrored sequences.

Example: compare with Program 36 (decreasing) and Program 38 next.

3. Console Formatting Drills

Practice concatenated digit output without spaces between numbers.

Example: add j + " " between digits for a spaced palindrome variant.

4. Padding character

Add leading spaces for center alignment once the two-loop structure works.

Example: print rows - i spaces before the descending loop.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count digits for rows = 5 — total is 1+3+5+7+9 = 25 = 5².

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row validation.

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

Pro Tip: when an interviewer asks for patterns, explain the 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 bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i and both inner loops on paper for rows = 3 before coding — watch how each row grows symmetrically.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Two Inner Loops Per Row

    Descending loop (j > 1) must run before ascending loop (j <= i).

  2. 2. Call Number.isFinite

    Avoid undefined behavior when the user types letters instead of a number.

  3. 3. Keep newline outside inner loops

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

  4. 4. Trace halves on Paper

    Write left half (i..2) and right half (1..i) for each row before coding.

  5. 5. Dry-Run rows = 3

    Trace i = 1..3 on paper before coding the full rows = 5 demo.

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

Common Pitfalls

Mistakes that commonly break palindrome number triangles.

  1. 1. Newline Inside an Inner Loop

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

    → Use line += j; console.log(line) only after both inner loops.

  2. 2. Wrong Loop Order

    Running ascending before descending breaks the palindrome symmetry.

    → Always append descending j = i..2 first, then ascending j = 1..i.

  3. 3. Wrong Descending Bound

    Using j >= 1 in the first loop duplicates the center digit.

    → Keep for (let j = i; j >= 2; j--) — stop at 2, let the ascending loop print 1.

  4. 4. Including 1 Twice

    Starting the descending loop at j >= 1 appends 1 twice in the middle.

    → Descending stops at j > 1; ascending starts at j = 1.

  5. 5. Bare parseInt(prompt())

    Letters or empty input yield NaN with bare parseInt(prompt(), 10).

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

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 — only the ascending loop runs.

rows = 0

Empty pattern

Outer loop never runs when rows < 1 — print nothing or show a message.

Negative

rows < 1

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

rows = 2

Smallest triangle

Two rows: 1 and 212.

Bad input

Non-numeric input

Bare parseInt(prompt(), 10) yields NaN on bad input — validate with Number.isFinite first.

Large rows

Large row count

Total digits = rows² — grows quadratically with rows.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Right-aligned decreasing

  • Review Program 36
  • Right-aligned triangle with decreasing sequences

2. Next in series

  • Continue with Program 38
  • Next pattern in the number-pattern series

3. Palindrome trace

  • Prove on paper: row i has 2i - 1 digits
  • Left half = i..2, right half = 1..i

4. Safe input loop

  • Validate rows >= 1 after reading input
  • Then draw the triangle

Notes

  • Palindrome rule. Outer i = 1..rows. Descending j = i..2, then ascending j = 1..i — row i appends 2i - 1 digits.
  • line += j stays on the line; console.log(line) advances — mix them carefully.
  • Validate rows >= 1 for interactive programs; rows = 1 prints a single 1.
  • Center digit is always 1 — compare with Program 36 where each row restarts from rows.

Quick Takeaway: outer i = 1..rows, desc j = i..2, asc j = 1..i, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The palindrome number triangle is a compact lesson in symmetry: append descending i..2, then ascending 1..i, and end each row with console.log(line). Master the fixed-rows version, then try user input and a smaller trace demo.

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

Descending loop must stop at j > 1 — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for (let i = 1; i <= rows; i++) in the outer loop
  • Left: for (let j = i; j >= 2; j--) line += j
  • Right: for (let j = 1; j <= i; j++) line += j
  • Validate parseInt(prompt(), 10) with Number.isFinite
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call console.log(line) inside an inner loop
  • Run ascending loop before descending loop
  • Use j >= 1 in the descending loop (duplicates 1)
  • Ignore bad prompt() input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this palindrome triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

1..i asc

Right half

Code
0 03

2i - 1

Digits/row

Code
04

Row break

console.log(line) after both inner loops

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Each row reads the same forward and backward. For example, 4321234 is symmetric around the center digit 1.
First, a loop appends i down to 2 (left half). Then another loop appends 1 up to i (right half). Together they create a mirrored sequence.
The first loop appends 4 3 2, and the second loop appends 1 2 3 4, which together form 4321234.
Row i appends 2i - 1 digits — one more than the previous row.
Program 36 is right-aligned with decreasing sequences. Program 37 builds a symmetric palindrome on each row with two inner loops.
Replace 5 with rows in the outer loop bound — see Example 2.
O(n²) for n rows because total digits appended are 1 + 3 + 5 + ... + (2n-1) = n².
Use parseInt with Number.isFinite or validate the raw string before converting so bad input does not produce NaN.
Only one row prints — a single digit 1.

Did you Know? 🔊

Each row is a palindrome: append i down to 2, then 1 up to i. Row i appends 2i - 1 digits — total digits across all rows = .

Continue to Program 38

Move on to the sequential decreasing-width triangle in the JavaScript number-pattern series.

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