Centered Alphabet Palindrome Pyramid (A, ABA, ABCBA, ...) in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Mirror Loops

What You’ll Learn

Each row is a centered palindrome of letters: row 0 prints A, row 1 prints ABA, row 2 prints ABCBA, until the bottom row shows ABCDEDCBA for five rows. Leading spaces (rows - 1 - r) center the pyramid; ascend and descend loops mirror letters without duplicating the peak. Compare with Program 18 (left-aligned palindrome pyramid). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Palindrome Rule

A..peak..A

Each row ascends from A to the peak, then descends from peak - 1 back to A.

Leading Spaces

rows - 1 - r

line += " ".repeat(rows - 1 - r) centers each palindrome row under the apex.

Ascend Loop

A..peak

for (let code = base; code <= peak; code++) appends letters up to and including the peak.

Descend Loop

peak-1..A

for (let code = peak - 1; code >= base; code--) mirrors back without repeating the peak.

Live Preview

1–26 rows

Pick a row count and draw the centered palindrome pyramid in the browser instantly.

O(n²)

Complexity

Row r prints 2r + 1 letters; total letters = O(n²); extra memory stays O(1).

Introduction

A centered alphabet palindrome pyramid prints each row as a mirror string of letters, padded with leading spaces so the shape is centered. Row 0 prints A; each next row adds one more letter to the peak and mirrors back - ABA, ABCBA, and so on.

In JavaScript you solve it with an outer loop over row index r, a space prefix, two inner loops for ascend and descend, and charCodeAt(0)/String.fromCharCode() - or build left and right strings and concatenate for clarity.

Why it matters?

It combines three classic pattern skills - centering with spaces, ascending sequences, and mirror loops that skip the peak - the same building blocks used in diamonds, hollow pyramids, and symmetric ASCII art. Compare with Program 18 to see how centering transforms the same palindrome rows.

Key Highlights

Leading Spaces

" " * (rows - 1 - r) - row 0 gets rows - 1 spaces; bottom row gets none.

Ascend Half

for (code = base; code <= peak; code++) - appends A through the row peak letter.

Descend Half

for (code = peak - 1; code >= base; code--) - mirrors back starting below the peak.

No Peak Duplicate

Descend starts at peak - 1 so ABCBA stays a true palindrome.

In short: set base = "A".charCodeAt(0), loop r from 0 to rows - 1, append (rows - 1 - r) spaces, ascend A..peak, descend (peak-1)..A, then console.log(line) for the newline.

📝 Problem & Approach

Given a positive integer rows, print a centered pyramid of rows lines. Row r prints (rows - 1 - r) leading spaces, then letters from A up to String.fromCharCode("A".charCodeAt(0) + r), then back down from peak - 1 to A.

JavaScript
// First 5 rows (centered)
    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows (peak letter runs A through the rows-th letter). Clamp to 1–26 for A–Z demos.
Printed outputtextCentered palindrome pyramid: each row is a mirror string with leading spaces - widest row has 2*rows - 1 letters.

Minimal workflow

Pseudocode
base = "A".charCodeAt(0)
for r from 0 to rows-1:
    append (rows-1-r) spaces
    peak = base + r
    for code from base to peak: append String.fromCharCode(code)
    for code from peak-1 down to base: append String.fromCharCode(code)
    console.log(line)

Approach comparison

ApproachIdeaBest for
Ascend + descend loopsTwo for loops with line += String.fromCharCode(code)Learning mirror loops and peak-off-by-one
Left/right stringsBuild left/right strings then concatenateClearer debugging and row inspection
Program 18 contrastSee Program 18 (left-aligned palindrome)Same palindrome logic without centering spaces

⚡ Quick Reference

GoalPattern
Leading spacesline += " ".repeat(rows - 1 - r)
Outer loop (row index)for (let r = 0; r < rows; r++)
Peak letter codepeak = base + r
Ascend loopfor (let code = base; code <= peak; code++) line += String.fromCharCode(code)
Descend loopfor (let code = peak - 1; code >= base; code--) line += String.fromCharCode(code)
End the rowconsole.log(line)
String variant" ".repeat(...) + left + right

📋 Leading Spaces vs Ascend vs Descend

Three parts of every row - pick the mental model that clicks for you.

Leading spaces
rows - 1 - r
centers row

Top row gets the most padding; bottom row aligns flush left before letters.

Ascend loop
base..peak
A, AB, ABC...

Prints letters from A up to and including the row peak.

Descend loop
peak-1..base
mirror half

Walks back down from one below the peak - avoids duplicating the center letter.

Program 18 contrast
no spaces
left-aligned

Same palindrome rows - see Program 18 without centering.

Context

When This Pattern Shows Up

Reach for centered palindrome pyramids when teaching mirror loops, spacing, and symmetric row building after diagonal patterns.

  1. After Program 31

    Program 31 places letters on two diagonals forming an X. This pattern builds full palindrome strings centered with leading spaces.

  2. Mirror loop practice

    Master the peak - 1 start index before tackling full diamonds and hollow shapes.

  3. Centering with spaces

    The (rows - 1 - r) space formula appears in centered stars, numbers, and diamond patterns.

  4. Gateway to Program 33

    Next pattern widens letter pairs - another symmetric triangle variation.

  5. Not a UI layout tool

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

Key benefit: one program that combines centering spaces with mirror loops - the same two skills used in diamond patterns, hollow pyramids, and symmetric ASCII art far beyond alphabet demos.

🔮 Live Preview

Choose a row count between 1 and 26 and draw the centered alphabet palindrome pyramid in the browser.

Try 5 (A through ABCDEDCBA) or 3 (A, ABA, ABCBA). Up to 26 rows use A–Z.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed five rows with centering spaces and mirror loops, prompt input, and a left/right string-build variant for clarity. Click View Output to reveal sample console results, or Try it Yourself to run in the browser editor.

📚 Getting Started

Print five rows of the centered alphabet palindrome pyramid with leading spaces and mirror loops.

Example 1 — Fixed rows = 5

Hard-coded height - ideal for first demos and screenshots.

JavaScript
let rows = 5;
rows = Math.max(1, Math.min(rows, 26));

const base = "A".charCodeAt(0);

for (let r = 0; r < rows; r++) {  // 0..4
  let line = "";

  // Centering spaces
  line += " ".repeat(rows - 1 - r);

  const peak = base + r;

  // Ascend: A..peak
  for (let code = base; code <= peak; code++) {
    line += String.fromCharCode(code);
  }

  // Descend: (peak-1)..A
  for (let code = peak - 1; code >= base; code--) {
    line += String.fromCharCode(code);
  }

  console.log(line);
}
Try it Yourself

How It Works

The outer loop walks row index r from 0 to 4. For each row, line += " ".repeat(rows - 1 - r) centers the palindrome, then peak = base + r sets the row peak letter. The ascend loop appends A through the peak; the descend loop mirrors from peak - 1 back to A without duplicating the center. Row 0 prints only A with four leading spaces; row 4 prints the full ABCDEDCBA with no spaces.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read rows and clamp to 1–26. Validate parseInt(prompt(), 10) with Number.isFinite in real apps.

JavaScript
let rows = parseInt(prompt("Enter number of rows (max 26):"), 10);
if (!Number.isFinite(rows)) {
  console.log("Please enter a whole number.");
} else {
  rows = Math.max(1, Math.min(rows, 26));

  const base = "A".charCodeAt(0);

  for (let r = 0; r < rows; r++) {
    let line = "";
    line += " ".repeat(rows - 1 - r);
    const peak = base + r;
    for (let code = base; code <= peak; code++) {
      line += String.fromCharCode(code);
    }
    for (let code = peak - 1; code >= base; code--) {
      line += String.fromCharCode(code);
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same centered palindrome core as Example 1; only the row count comes from prompt. Three rows produce A, ABA, and ABCBA with 2, 1, and 0 leading spaces respectively.

⚡ String Join Variant

Build left and right halves as strings, then log spaces + left + right.

Example 3 — Left/Right String Variant

Build ascend and descend halves as strings - same logic, easier row inspection.

JavaScript
let rows = 5;
rows = Math.max(1, Math.min(rows, 26));

const base = "A".charCodeAt(0);

for (let r = 0; r < rows; r++) {
  const peak = base + r;
  let left = "";
  for (let code = base; code <= peak; code++) {
    left += String.fromCharCode(code);
  }
  let right = "";
  for (let code = peak - 1; code >= base; code--) {
    right += String.fromCharCode(code);
  }
  console.log(" ".repeat(rows - 1 - r) + left + right);
}
Try it Yourself

How It Works

left builds the ascend half and right builds the descend half as strings. Concatenating with leading spaces produces identical output to Examples 1 and 2, but you can inspect left and right separately during debugging.

🧠 How the Algorithm Prints Rows

1

Set up bounds

Clamp rows, then set base = "A".charCodeAt(0) for the alphabet starting point.

base / rows
2

Print leading spaces

line += " ".repeat(rows - 1 - r) centers row r before any letters.

Center
3

Ascend and descend

Ascend A..peak, then descend (peak-1)..A with line += String.fromCharCode(code) in both loops.

Mirror
4

New line

console.log(line) ends the row after spaces and both letter loops finish; the outer loop advances r.

Break
=

Pattern complete

Total letters: 1 + 3 + 5 + ... + (2n-1) = n²O(n²) time, O(1) extra memory (loop version).

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of r and see how leading spaces, peak letter, ascend, and descend produce each centered palindrome row.

rpeakspacesascenddescendfull row
0A4A(none)A
1B3ABAABA
2C2ABCBAABCBA
3D1ABCDCBAABCDCBA
4E0ABCDEDCBAABCDEDCBA

Highlight rows: r = 0 (4 spaces, peak A, A only), r = 2 (2 spaces, peak C, ABCBA), r = 4 (0 spaces, peak E, ABCDEDCBA). Total letters printed: 1 + 3 + 5 + 7 + 9 = 25 = rows² for rows = 5.

Use Cases

Where centered palindrome pyramids show up beyond the homework prompt.

1. After Program 31

Program 31 uses diagonal columns for an X shape. This pattern builds full palindrome strings centered with spaces.

Example: compare diagonal X grid vs centered ABCBA rows side by side.

2. Mirror loop practice

Reinforce the peak - 1 descend start before tackling diamonds and hollow pyramids.

Example: trace row 2 (r=2) on paper: spaces=2, ascend=ABC, descend=BA.

3. Program 18 contrast

Same palindrome rows without centering - see Program 18.

Example: add line += " ".repeat(rows - 1 - r) to Program 18 to get this shape.

4. Full diamond extension

Mirror the pyramid downward to close a full alphabet diamond.

Example: after the top half, loop r from rows-2 down to 0 with the same row logic.

5. Complexity intuition

Sum of odd row lengths makes O(n²) concrete for beginners.

Example: 5 rows → 25 letters printed (1+3+5+7+9).

6. Interview warm-up

Classic nested-loop question that tests mirror logic and centering spaces.

Example: explain why descend starts at peak - 1 without running code.

Pro Tip: say “spaces, then up to peak, then down from peak minus one” before coding - that story prevents duplicated peaks and wrong indentation.

Advantages

Why this pattern earns a spot after the alphabet X pattern from Program 31.

  1. 1. Teaches Mirror Loops

    Ascend then descend with peak - 1 - a pattern reused in diamonds and hollow shapes.

  2. 2. Centered Symmetry

    Leading spaces create a visually balanced pyramid - every row aligns under the apex.

  3. 3. Two Implementations

    Direct print loops for learning; left/right string variant for clearer debugging.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters (string variant uses O(r) per row).

Pro Tip: when row 0 prints only A, the descend loop range is empty - that is correct, not a bug.

Usage Tips

Small habits that keep centered palindrome pyramid code clean.

  1. 1. Name peak explicitly

    Use peak = base + r - keeps ascend and descend loops readable.

  2. 2. Wrap parseInt(prompt(), 10) in try/except

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

  3. 3. Clamp rows early

    rows = Math.max(1, Math.min(rows, 26)) keeps demos inside A–Z.

  4. 4. Print spaces before letters

    line += " ".repeat(rows - 1 - r) must run before the ascend loop each row.

  5. 5. Dry-run rows = 3

    Trace A, ABA, ABCBA with 2, 1, 0 spaces on paper before coding larger demos.

Pro Tip: if the pyramid leans left, check the space count - it should be rows - 1 - r, not r.

Common Pitfalls

Mistakes that commonly break centered alphabet palindrome pyramids.

  1. 1. Duplicating peak in descend loop

    Starting descend at peak instead of peak - 1 prints ABCCBA - a doubled center letter.

    → Use for (let code = peak - 1; code >= base; code--) so the peak appears only once.

  2. 2. Wrong space count

    Using r spaces or rows - r misaligns the pyramid - rows lean or over-indent.

    → Use rows - 1 - r leading spaces so row 0 gets the most padding.

  3. 3. Hardcoded ASCII 65

    Magic numbers like String.fromCharCode(65 + r) work but break readability and lowercase variants.

    → Use base = "A".charCodeAt(0) and String.fromCharCode(base + r) instead of raw ASCII values.

  4. 4. Blind parseInt(prompt(), 10)

    Non-numeric input yields NaN with bare parseInt(prompt(), 10).

    → Validate with Number.isFinite and clamp the range.

  5. 5. Forgetting leading spaces

    Printing only palindrome letters without spaces produces a left-aligned pyramid like Program 18.

    → Print " " * (rows - 1 - r) before the ascend loop on every row.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single letter

Output is just A (with rows - 1 spaces) - descend loop range is empty when peak equals base.

rows = 0

Empty pattern

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

rows = 26

Full alphabet

26 rows with peak Z - bottom row prints ...Z...Z... with no leading spaces.

rows > 26

Past Z

Clamp to 26 or define a wrap/error policy before printing.

Bad input

Non-numeric input

Use Number.isFinite before clamping rows.

Case

Lowercase variant

Same loops work with base = "a".charCodeAt(0) and lowercase output.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 18

  • Program 18: left-aligned palindrome (A, ABA, ABCBA)
  • This pattern: same rows with leading spaces to center
  • See Program 18

2. Implement string variant

  • Rewrite Example 1 using left and right strings
  • Verify identical output for rows=5

3. Compare with Program 31

  • Program 31: diagonal X with spaced grid
  • This pattern: full palindrome strings centered
  • See Program 31

4. Continue to Program 33

  • Next pattern - widening alphabet triangle
  • Builds on symmetric shape ideas
  • See Program 33

Notes

  • Letter count. Row r prints 2r + 1 letters. Over n rows the total is .
  • Descend loop: for (let code = peak - 1; code >= base; code--) - include A by stopping when code < base.
  • left + right string variant is equivalent to the direct-print version - use whichever fits your lesson.
  • Clamp to 26 rows for A–Z demos; compare with Program 18 for the left-aligned version without spaces.

Quick Takeaway: outer loop sets r, print (rows - 1 - r) spaces, ascend A..peak, descend (peak-1)..A, then break the line - that is the whole centered palindrome pyramid.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Ascend + descend loops (Examples 1–2)O(rows²)O(1)
String variant (Example 3)O(rows²)O(r) for left/right strings per row
Wrap Up

🎉 Conclusion

The centered alphabet palindrome pyramid combines centering spaces with mirror loops - ascend A..peak, descend (peak-1)..A. Master the direct-print version, then try the left/right string variant for clearer debugging.

Practice the three examples above, then continue to Program 33 in the alphabet pattern series.

Print leading spaces, run ascend and descend loops with peak - 1, clamp rows to 26, and compare with Program 18 (left-aligned palindrome pyramid).

💡 Best Practices

✅ Do

  • Set base = "A".charCodeAt(0), clamp rows to 1–26
  • Append (rows - 1 - r) leading spaces each row
  • Ascend for (code = base; code <= peak; code++), descend for (code = peak - 1; code >= base; code--)
  • Use line += String.fromCharCode(code) in letter loops; console.log(line) after
  • Compare output with Program 18 to verify centering
  • Try the left/right string variant for debugging

❌ Don’t

  • Start descend at peak - duplicates the center letter
  • Hardcode ASCII 65 instead of "A".charCodeAt(0)
  • Use wrong space count - pyramid will lean left or right
  • Skip leading spaces - output matches Program 18, not centered
  • Call console.log inside the letter loops
  • Let rows exceed 26 without a defined policy

Key Takeaways

Knowledge Unlocked

Five things to remember about this centered palindrome pyramid

Print the centered pyramid the beginner-friendly way.

5
Core concepts
  02

Leading spaces

rows - 1 - r

Center
↑A 03

Ascend loop

base..peak

Code
↓A 04

Descend loop

peak-1..base

Code
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Each row is a palindrome of letters (A, ABA, ABCBA, ...) padded with leading spaces so the pyramid is centered. Row r prints (rows-1-r) spaces, then A..peak, then (peak-1)..A.
The ascend loop already prints the peak letter. Starting the mirror at peak-1 avoids duplicating the center character - ABCBA not ABCCBA.
Print (rows - 1 - r) spaces before the letters. Row 0 gets the most spaces; the bottom row gets zero.
Program 18 prints the same palindrome rows left-aligned with no leading spaces. Program 32 adds (rows-1-r) spaces to center the pyramid.
Each row peak is String.fromCharCode('A'.charCodeAt(0) + r). With rows > 26 you would need characters beyond Z unless you define a wrap or error policy.
line += String.fromCharCode(code) keeps each letter on the same row. console.log(line) ends the row after spaces, ascend, and descend finish.
O(n^2) where n is rows. Row r prints about 2r+1 letters plus spaces; the sum of odd lengths is n^2.
Use parseInt(prompt(), 10) and check Number.isFinite, then clamp rows between 1 and 26.

Did you Know? 🔊

Row r prints (rows - 1 - r) leading spaces, then letters from A up to the peak String.fromCharCode('A'.charCodeAt(0) + r), then back down to A starting at peak - 1 so the peak is not duplicated.

Continue to Program 33

Next up: the widening alphabet triangle - build on symmetric shape ideas from this tutorial.

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