Palindromic Alphabet Pyramid (BAB) in JavaScript

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

What You’ll Learn

Build each row as a palindrome by stitching a descending run (i down to B) with an ascending run (A up to i), so a single A sits at the center. This version prints letters with no extra spacing (unlike right-aligned patterns that use 2-column cells). Compare Program 18 (another palindrome style) and Program 16 (centering with pads). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Palindrome rows

A, BAB, CBABC, … EDCBABCDE.

Two Wings

Down, then up

Descend i..B; ascend A..i.

Single A

j > 'A'

Descending stops before A so the center is not doubled.

Odd Lengths

1, 3, 5…

Row length is 2r-1 for row number r.

Live Preview

1–8 rows

Pick a height and draw the palindrome pyramid.

n² Chars

Complexity

Total printed characters = n² → O(n²).

Introduction

A palindromic alphabet pyramid prints rows that read the same forwards and backwards, with peak letters growing from A outward around a single center A.

In JavaScript you solve it with nested loops over letter codes: descend from the row peak to B, then ascend from A to the peak using charCodeAt/fromCharCode.

Why it matters?

It teaches how two ranges join without duplicating the center — a common bug when building palindrome strings or patterns.

Key Highlights

Descend

Left wing: peak down to B.

Ascend

Center A plus right wing.

One A

Stop descending before A.

Left Align

No pads in the classic sample.

In short: for each peak i, append i..B, then A..i, then call console.log(line).

📝 Problem & Approach

Given a row count n (or fixed A–E), print a left-aligned palindromic alphabet pyramid with peak letters growing each row.

JavaScript
// Five rows (left-aligned; no cell padding)
// A
// BAB
// CBABC
// DCBABCD
// EDCBABCDE

Inputs & Outputs

ItemTypeDescription
nintNumber of rows (1..26 for A..Z). Peak of row r is String.fromCharCode("A".charCodeAt(0) + r).
Printed outputtextPalindrome rows of odd length 1, 3, 5, …

Minimal workflow

Pseudocode
for i from base to peak:
    line = ""
    for j from i down while j > base:
        line += String.fromCharCode(j)
    for j from base to i:
        line += String.fromCharCode(j)
    console.log(line)

Approach comparison

ApproachIdeaBest for
Descend then ascend (this page)i..B then A..iMatching the BAB / EDCBABCDE sample
Ascend then descendA..peak then peak-1..AProgram 18-style palindromes

⚡ Quick Reference

GoalPattern
Outer rowsfor (let i = base; i <= top; i++)
Left wingfor (let j = i; j > base; j--) line += String.fromCharCode(j)
Center + rightfor (let j = base; j <= i; j++) line += String.fromCharCode(j)
End rowconsole.log(line)
Other palindromeSee Program 18

📋 Descend vs Ascend vs console.log

Same row - three roles that build the palindrome.

j = i..B
left

Descending wing; stops before A

j = A..i
right

Center A plus ascending wing

j > 'A'
once

Guarantees a single center A

console.log
break

Ends the row after both wings

Context

When This Pattern Shows Up

Reach for this when teaching palindrome construction with two joined ranges.

  1. After reverse pyramids

    Reuse descending ranges, then mirror them ascending.

  2. Center-join drills

    Practice stopping one loop so the join character prints once.

  3. Compare with Program 18

    Same palindrome idea; different wing order.

  4. Odd-length rows

    Show why 1+3+5+…+(2n-1) equals n².

  5. Not a UI layout tool

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

Key benefit: stopping the descending loop before A is the cleanest way to keep a single center character in this style of palindrome.

🔮 Live Preview

Choose between 1 and 8 rows and draw the palindromic alphabet pyramid in the browser.

Try 5 (through E) or 4 (through D). Max 8 keeps rows readable.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed A–E, user-chosen row count, and a spaced variant. Click View Output to reveal sample console results, or Try it Yourself to run in the browser editor.

📚 Getting Started

Print five palindromic rows from A through E.

Example 1 — Fixed A–E

Two loops per row: descending (i..B), then ascending (A..i). The descending loop stops before A, so A appears once.

JavaScript
const base = "A".charCodeAt(0);
const top = "E".charCodeAt(0);

for (let i = base; i <= top; i++) {
  let line = "";
  for (let j = i; j > base; j--) {
    line += String.fromCharCode(j);
  }
  for (let j = base; j <= i; j++) {
    line += String.fromCharCode(j);
  }
  console.log(line);
}
Try it Yourself

How It Works

When i is 'C', the left wing appends C B and the right wing appends A B CCBABC. The center A comes only from the ascending loop.

📈 Practical Variant

Let the user choose how many rows to print.

Example 2 — Row Count Input

Cap at 26 for A–Z. Validate parseInt(prompt()) with Number.isFinite in real apps.

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

  for (let r = 0; r < n; r++) {
    const peak = base + r;
    let line = "";

    for (let ch = peak; ch > base; ch--) {
      line += String.fromCharCode(ch);
    }
    for (let ch = base; ch <= peak; ch++) {
      line += String.fromCharCode(ch);
    }

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

How It Works

Row index r maps to peak "A".charCodeAt(0) + r. Same descend/ascend rules; only the number of peaks changes.

⚡ Spaced Style

Same palindrome with a space after each letter for a wider look.

Example 3 — Spaced Letters

Useful when you want the shape to read more clearly in dense terminals.

JavaScript
const base = "A".charCodeAt(0);
const top = "E".charCodeAt(0);

for (let i = base; i <= top; i++) {
  let line = "";
  for (let j = i; j > base; j--) {
    line += String.fromCharCode(j) + " ";
  }
  for (let j = base; j <= i; j++) {
    line += String.fromCharCode(j) + " ";
  }
  console.log(line);
}
Try it Yourself

How It Works

Same wing logic; only the append format adds a trailing space after each letter. Trim the final space per row if you need a clean line end.

🧠 How the Algorithm Prints Rows

1

Outer loop picks the row peak

i goes from A to E (or your chosen height).

Peak
2

Print the left wing (descending)

Loop j = i..B appends the descending part. We stop at j > base so A is not appended here.

Down
3

Print the center + right wing (ascending)

Loop j = A..i appends the center A and then climbs back up to the peak letter.

Up
4

New line

console.log(line) ends the row so the next peak can grow both wings.

Break
=

One A in the middle

Row lengths are 1, 3, 5, 7, 9 for A..E, so total characters is for n rows.

🔎 Worked Walkthrough — A–E

Trace each row’s left wing, center+right wing, and full line.

iLeft (i..B)Right (A..i)Printed row
A(empty)AA
BBA BBAB
CC BA B CCBABC
DD C BA B C DDCBABCD
EE D C BA B C D EEDCBABCDE

Lengths: 1+3+5+7+9 = 25 = 5².

Use Cases

Where this palindromic pyramid shows up beyond the homework prompt.

1. Palindrome Labs

Clearest demo of joining two ranges around one center.

Example: flip > to >= and watch AA appear.

2. Pair with Program 18

Same mirror idea; different wing construction order.

Example: print both for n = 5 and compare.

3. Char Loop Practice

Outer and inner loops over ascending and descending char ranges.

Example: rewrite with int indexes for peak and offset.

4. Spacing Experiments

Add spaces or leading pads without changing the letter order.

Example: Example 3 spaced letters; Program 16 for centering.

5. Complexity Intuition

Odd-length rows make the n² total easy to see.

Example: 5 rows print 25 characters.

6. Bridge to Program 25

Next pattern switches back to a running sequential stream.

Example: continue to Program 25.

Pro Tip: say “down to B, then A up to the peak” before coding - that story prevents a duplicated center A.

Advantages

Why this pattern earns a spot after reverse and sequential pyramids.

  1. 1. Instant Visual Feedback

    A duplicated center or wrong wing order shows up immediately.

  2. 2. Two Clear Wings

    Descend and ascend are easy to explain separately.

  3. 3. Palindrome Practice

    A natural bridge to string-palindrome thinking.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop variables.

Pro Tip: learn the compact no-space version first; treat spacing and centering as optional visual upgrades afterward.

Usage Tips

Small habits that keep palindromic alphabet pyramids clean.

  1. 1. Keep j > 'A' on the Left Wing

    That single condition is what prevents a double center.

  2. 2. Cap Rows at 26

    Beyond Z you need a wrap/stop policy.

  3. 3. Use Number.isFinite

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

  4. 4. Do Not Assume Centering

    Classic output is left-aligned; add pads if you want a centered look.

  5. 5. Compare with Program 18

    If rows look like ABCBA instead of CBABC, you used the other wing order.

Pro Tip: if you see BAAB or CBABBC, the descending loop almost certainly used >= 'A'.

Common Pitfalls

Mistakes that commonly break palindromic alphabet pyramids.

  1. 1. Using j >= 'A' on the Left Wing

    Duplicates the center A (BAAB, CBABBC, …).

    → Keep the descending condition as j > base.

  2. 2. Swapping Wing Order Accidentally

    You may get Program 18-style rows instead of BAB / CBABC.

    → Descend first, then ascend for this sample.

  3. 3. Assuming Output Is Centered

    Classic rows hug the left margin.

    → Add leading spaces (or see Program 16) for a centered look.

  4. 4. Blind parseInt(prompt())

    Letters or empty input yield NaN.

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

  5. 5. Letting n Exceed 26

    Peaks walk past Z without a defined policy.

    → Cap at 26 or define wrap/stop behavior.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single letter

Output is just A (left wing empty).

n = 5

Classic sample

Through EDCBABCDE (25 characters).

n = 4

Smaller pyramid

Through DCBABCD (Example 2).

n = 26

Full alphabet

Peak reaches Z; still one center A per row.

Bad input

Non-numeric prompt()

parseInt(prompt()) yields NaN - check with Number.isFinite.

Case

Lowercase

Same loops with base 'a'.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Flip the wing order

  • Build A..peak then peak-1..A
  • Compare with Program 18

2. Center the pyramid

  • Add leading spaces per row
  • See Program 16 for pad ideas

3. Spaced letters

  • Print a space after each letter (Example 3)
  • Keep the same wing logic

4. Continue to Program 25

  • Sequential decreasing alphabet triangle
  • See Program 25

Notes

  • Two wings. Descend peak..B, then ascend A..peak, with one shared center A.
  • Use j > base on the descending loop - never >= for this sample.
  • Row lengths are odd: 1, 3, 5, … and total characters over n rows is n².
  • Unlike Programs 22–23, this classic sample does not use fixed-width cells.

Quick Takeaway: for each peak, print descending letters down to B, then ascending letters from A to the peak, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Spaced letters (Example 3)O(n²)O(1)

Total printed characters are 1+3+…+(2n-1) = n², so time is O(n²).

Wrap Up

🎉 Conclusion

The palindromic alphabet pyramid is a small nested-loop exercise with lasting payoff: descending and ascending wings joined around a single center A. Master the classic A…E sample, then try user input and spaced letters.

Practice the three examples above, then continue to Program 25’s sequential decreasing alphabet triangle.

Descend to B, ascend from A, keep one center A with j > base, then break the line.

💡 Best Practices

✅ Do

  • Stop the descending loop at j > base
  • Print ascending A..i for the center and right wing
  • Cap input rows at 26 for A–Z
  • Validate parseInt(prompt()) with Number.isFinite for user input
  • State O(n²) / n² characters when asked about complexity

❌ Don’t

  • Use j >= 'A' on the left wing
  • Assume the classic sample is centered
  • Let n exceed 26 without a wrap/stop rule
  • Confuse this wing order with Program 18
  • Call console.log(line) inside either wing loop

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

Print the palindromic alphabet pyramid the beginner-friendly way.

5
Core concepts
A 02

Center

One A only

Code
03

Condition

j > 'A'

Code
04

console.log

Ends each row

I/O
O 05

Complexity

n² chars

Analysis

❓ Frequently Asked Questions

The first loop appends descending letters from the row peak down to B. The second appends ascending from A through i. Together they mirror around a single A.
The ascending loop already appends A. Stopping the descending loop before A avoids duplicating the center character.
The descending loop stops at j > base, and the ascending loop starts at base. That prevents appending A twice at the join.
For row letter i, length is 2*(i-base)+1, so rows grow as 1, 3, 5, 7, 9 for A..E.
Change the outer loop upper bound from E to your target letter (like H), or use the row-count prompt() variant.
Program 18 typically builds A..peak then peak-1..A. This pattern descends to B first, then ascends A..i, still mirroring around a single A.
O(n^2) for n rows because total printed characters are 1+3+...+(2n-1) = n^2.
No - the classic version is left-aligned with no leading spaces. Add pad spaces (or see Program 16) if you want a centered pyramid.

Did you Know? 🔊

Outer i runs A.. E. First inner loop appends the left wing (i down to B) by stopping at j > base. Second inner loop appends A.. i. Because the reverse loop stops before A, the center A is not duplicated.

Continue to Alphabet Pattern 25

Next up: sequential decreasing alphabet triangles with a running k++ stream.

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