Palindrome Alphabet Pyramid in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
k = i - 1 mirror

What You'll Learn

This pattern prints a centered palindrome per row: first it grows from A up to the row letter (A..i), then it mirrors back down (i-1..A). Starting the second loop at i - 1 avoids duplicating the middle character.

⭐ Pattern Output

Output
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
1

Node.js / console version

Two inner loops: forward A..i, then reverse i-1..A:

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

for (let i = A; i <= top; i++) {
  let line = "";
  for (let j = A; j <= i; j++) line += String.fromCharCode(j);
  for (let k = i - 1; k >= A; k--) line += String.fromCharCode(k);
  console.log(line);
}
2

Browser version (document.write)

Same logic as the reference, using character codes:

HTML
<!DOCTYPE html>
<html>
<body>
<script>
  const A = 65;
  const top = 69;
  for (let i = A; i <= top; i++) {
    for (let j = A; j <= i; j++) document.write(String.fromCharCode(j));
    for (let k = i - 1; k >= A; k--) document.write(String.fromCharCode(k));
    document.write("<br>");
  }
</script>
</body>
</html>

🧠 How It Works

1

Outer loop: rows

i goes from A to E.

5 rows
2

Forward: A..i

Print letters from A up to the row letter.

Left half
3

Mirror: i-1..A

Start at i - 1 to avoid duplicating the peak letter.

Right half
=

Palindrome row

Every row reads the same forwards and backwards.

💡 Tips for Enhancement

Try These

  • Change top to print more rows (e.g. 'G')
  • Add spaces between letters to make the symmetry easier to see
  • Compare with Program 15 (another mirror-style pattern)

Avoid

  • Starting the second loop at i (it duplicates the peak letter)
  • Mixing lowercase/uppercase codes without updating bounds

Key Takeaways

1

Two loops per row: forward then reverse.

2

k = i - 1 prevents duplicate centers.

3

Row lengths are odd: 1, 3, 5, 7, 9.

4

Total characters printed: 25 for A..E.

❓ Frequently Asked Questions

Because the first loop already printed i. Starting at i - 1 produces ABCBA instead of ABCCBA.
For n rows the work is \(1 + 3 + \u2026 + (2n-1) = n^2\), so O(n²).
Yes. Use 'a'.charCodeAt(0) as the start and adjust the end to 'e'.

More JavaScript alphabet patterns

Browse the full list or try star and number pattern tutorials.

Next: Program 19 →
Did you know?

The total characters printed for A..E is \(5^2 = 25\) because the row lengths are the first five odd numbers.

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.

10 people found this page helpful