Centered Square Number Pyramid in JavaScript

What You’ll Learn
How to print a centered pyramid of square numbers, where values increment as 1², 2², 3² and so on.
You’ll also see how odd row widths (1, 3, 5, 7, 9) make centering straightforward.
⭐ Pattern Output
For this example, the pattern looks like this:
1
4 9 16
25 36 49 64 81
100 121 144 169 196 225 256
289 324 361 400 441 484 529 576 625Complete JavaScript Program
We print indentation first, then print count squares. A counter m increases each time so the squares continue across rows.
let m = 1;
for (let count = 1; count <= 9; count += 2) {
let line = "";
for (let s = count; s < 9; s++) {
line += " ";
}
for (let k = 1; k <= count; k++) {
line += String(m * m).padStart(3, " ") + " ";
m++;
}
console.log(line.trimEnd());
}🧠 How It Works
Initialize m
m = 1 is the current number whose square we print.
Outer loop increases width by 2
count = 1, 3, 5, 7, 9 controls how many squares appear on each row.
Indentation loop centers the row
Printing spaces while s < 9 creates left padding that shrinks as count grows.
Print squares and increment m
Each printed cell uses m*m, then m++ advances to the next square.
Centered row of squares
Numbers are squares of consecutive integers, laid out in a centered pyramid.
Variation — Browser (fixed-width <div> cells)
In the browser, fixed-width cells help keep 3-digit squares aligned:
<!DOCTYPE html>
<html>
<head>
<style>
.cell {
display: inline-block;
text-align: center;
width: 36px;
}
</style>
</head>
<body>
<script>
var i, j, k;
var m = 1;
for (i = 1; i <= 9; i += 2) {
for (j = i; j < 9; j++)
document.write(" ");
for (k = 1; k <= i; k++) {
document.write("<span class='cell'>" + (m*m) + "</span>");
m++;
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change the maximum width (9) to print a larger pyramid
- Print cubes instead of squares (use
m*m*m) - Add color styling to highlight perfect squares visually
- Use DOM elements instead of
document.writefor modern pages
Avoid
- Using variable-width spacing for 3-digit numbers (alignment breaks)
- Resetting
maccidentally inside the loop (sequence restarts) - Forgetting the line break after each row in browser mode
Key Takeaways
Squares are generated by printing m*m and incrementing m.
Odd row widths (1, 3, 5, ...) keep the pyramid symmetric.
Indentation is the key to centering.
Fixed-width cells help when values become 2-3 digits.
❓ Frequently Asked Questions
m to a different start value (for example, m = 3 starts at 9).Explore More JavaScript Number Patterns!
Square-number patterns combine simple math with loops—great practice for both.
1+3+5+...+(2n-1) = n². That’s why the pyramid prints 25 values and ends at 25² = 625.
12 people found this page helpful
