Centered Incremental Number Pyramid in JavaScript

What You’ll Learn
How to print a centered incremental number pyramid in JavaScript. The numbers continue increasing across rows: 1, then 2 3 4, then 5 6 7 8 9.
You’ll see how to combine a fixed-width inner loop with an outer loop that grows by 2 to keep the pyramid centered.
⭐ Pattern Output
For this example, the pattern looks like this:
1
2 3 4
5 6 7 8 9Complete JavaScript Program
We keep a counter k that increases each time we print a number. The inner loop prints either spaces (for left padding) or the next value of k.
let k = 1;
for (let i = 1; i <= 5; i += 2) {
let line = "";
for (let j = 5; j >= 1; j--) {
if (j > i) {
line += " ";
} else {
line += k + " ";
k++;
}
}
console.log(line.trimEnd());
}🧠 How It Works
Initialize the counter
let k = 1; stores the next number to print and increases across rows.
Outer loop grows row width
for (let i = 1; i <= 5; i += 2) makes the row contain 1 number, then 3, then 5.
Inner loop scans a fixed width
for (let j = 5; j >= 1; j--) ensures every row uses the same width, so centering is consistent.
Decide between spaces vs numbers
If j > i, we add padding spaces. Otherwise we append k and increment it.
Numbers flow across rows
The counter continues increasing, so the pyramid shows consecutive values instead of restarting each row.
Variation — Browser (document.write) Version
Print the same pattern in an HTML page using document.write and for spacing:
<!DOCTYPE html>
<html>
<body>
<script>
let k = 1;
for (let i = 1; i <= 5; i += 2) {
for (let j = 5; j >= 1; j--) {
if (j > i) {
document.write(" ");
} else {
document.write(k++ + " ");
}
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change the height by increasing the max
ivalue and inner-loop width - Restart numbering on each row by moving
kinside the outer loop - Add a fixed width for each number (like
String(k).padStart(2)) for alignment - Replace numbers with letters to create an alphabet pyramid
Avoid
- Forgetting that the inner loop width controls centering
- Printing raw spaces in browser mode (use
for consistent spacing) - Leaving trailing spaces (use
trimEnd()for console output)
Key Takeaways
A fixed-width inner loop makes centering easy and consistent.
Increasing the outer loop by 2 grows the pyramid by odd counts: 1, 3, 5…
A counter variable lets numbers continue across rows (instead of restarting).
You can print to the console or directly into the browser with document.write.
❓ Frequently Asked Questions
1 to 9.let k = 1; inside the outer loop so the counter resets for every row.Explore More JavaScript Number Patterns!
Practice nested loops with pyramids, triangles, and symmetric patterns to level up your logic.
Odd-number growth (1, 3, 5…) is a common trick for pyramids and diamonds. It keeps patterns symmetric around the center.
12 people found this page helpful
