Right Triangle Alphabet Pattern in JavaScript

What You'll Learn
Each row adds one more letter, from A up to the row’s last letter. The inner loop always starts at A and stops at the current outer index.
Total letters printed for n rows is \(1 + 2 + \cdots + n = \frac{n(n+1)}{2}\).
⭐ Pattern Output
When you run the program for five rows (A–E):
A
AB
ABC
ABCD
ABCDENode.js / console version
Uses let, builds each row in a string, and prints with console.log (no document.write):
const start = "A".charCodeAt(0);
const end = "E".charCodeAt(0);
for (let i = start; i <= end; i++) {
let line = "";
for (let j = start; j <= i; j++) {
line += String.fromCharCode(j);
}
console.log(line);
}Browser version (document.write)
Same logic as the classic tutorial: print into the HTML document. Save as .html and open in a browser, or use the live editor:
<!DOCTYPE html>
<html>
<body>
<script>
for (let i = 65; i <= 69; i++) {
for (let j = 65; j <= i; j++) {
document.write(String.fromCharCode(j));
}
document.write("<br>");
}
</script>
</body>
</html>🧠 How It Works
Character codes for A–E
65 is 'A', 69 is 'E'. The outer loop walks i from start to end so each row ends on the next letter.
Inner loop prints the row
for (let j = start; j <= i; j++) runs from A up to the current i. Each pass appends String.fromCharCode(j).
New line after each row
In the console example, console.log(line) adds a newline. In the browser example, document.write("<br>") breaks the line in HTML.
Growing rows
Row count matches the outer loop. Work is O(n2) for n rows because total characters are n(n+1)/2.
💡 Tips for Enhancement
Try These
- Build each row with a small array and
.join("")instead of+= - Parameterize the last letter so the height is not hard-coded
- After this pattern, try the next alphabet program in the series
- Compare with the right-angled star triangle (same loop shape)
Avoid
- Using
document.writeafter the document has loaded (it can wipe the page) - Mixing
varandletwithout reason in new code - Assuming ASCII codes if you need full Unicode beyond basic Latin letters
Key Takeaways
The inner loop always starts at A and ends at the current outer code i.
String.fromCharCode turns numeric codes into characters.
Total letters for n rows: \(n(n+1)/2\).
Console output uses console.log; HTML demos often use document.write for simplicity.
Time complexity is O(n²) for n rows.
❓ Frequently Asked Questions
"A".charCodeAt(0) avoids magic numbers and is easier to change if you switch letters.n rows, the inner loop does \(1 + 2 + \cdots + n = n(n+1)/2\) iterations, so the algorithm is O(n²).Next: JavaScript Alphabet Pattern 2
Continue to the next program in the alphabet pattern series.
In modern JavaScript, String.fromCodePoint handles code points above U+FFFF; fromCharCode is enough for A–Z.
10 people found this page helpful
