JavaScript Square Number Pyramid Pattern

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A square numbers pyramid appends consecutive perfect squares in odd-width rows, centered with leading spaces and fixed-width cells.

Remember
Rule: m += 1; append m²; row width = 2*r - 1; pad left

                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625     ← rows = 5

Unlike Program 40 (alternating 1/0), this pattern uses a running counter whose square is appended each time — total squares for n rows is n².

How to Solve It

Keep counter m outside the row loop. For each row, add leading spaces, then append 2*r - 1 squares with padStart(4).

MethodIdeaBest for
CenteredLeading spaces + padStart(4) squaresClassic pyramid demos
Left-alignedSkip leading spaces; keep padStartSimpler first dry-runs

Pseudocode

Pseudocode
m = 0
for r from 1 to rows:
    line = spaces of length 4 * (rows - r)
    repeat (2 * r - 1) times:
        m = m + 1
        append m*m padded to width 4
    print line

Cheat sheet

GoalPattern
Outer (rows)for (let r = 1; r <= rows; r++)
Leading pad" ".repeat(4 * (rows - r))
Odd widthfor (let k = 0; k < 2 * r - 1; k++)
Next squarem += 1; line += String(m * m).padStart(4, " ");
End the rowconsole.log(line);
Total squaresrows * rows (= 1+3+…+(2n-1))

Printing Numbers vs Starting a New Line

APIEffectUse for
line += …Stays on the same rowPads and each m² cell
console.log(line)Ends the current rowAfter the row is fully built

Append without a newline, then end the row once.

Live Preview

Change the row count and the square pyramid updates instantly.

Whole numbers from 1 to 7. Tap a chip or type a value — the preview redraws as you go.

Live result rows = 5 · 25 squares
                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625

Worked Walkthrough

Trace three rows when rows = 5 — watch width, pads, and the next squares from m.

Row rWidthm valuesSquares
1111
232, 3, 44 9 16
355..925 36 49 64 81

Leading pad length is 4 * (rows - r) spaces so each cell stays 4 columns wide under the centered pyramid.

JavaScript Programs

Three complete programs: fixed rows = 5, prompt input, and a left-aligned variant. Use View Output for samples, or Try It Yourself to edit and run live.

Example 1 — Fixed rows = 5

Hard-coded height — centered pads, odd widths, running m * m.

JavaScript
const rows = 5;
let m = 0;

for (let r = 1; r <= rows; r++) {
  let line = " ".repeat(4 * (rows - r));
  for (let k = 0; k < 2 * r - 1; k++) {
    m += 1;
    line += String(m * m).padStart(4, " ");
  }
  console.log(line);
}
Try It Yourself

How It Works

1. Keep one counter. m lives outside the outer loop so squares continue across rows.

2. Center the row. " ".repeat(4 * (rows - r)) shifts narrow rows right.

3. Append odd-width squares. Inner loop runs 2 * r - 1 times; each pass does m += 1 and appends m * m with padStart(4).

Example 2 — User Input Rows

Read the row count with prompt and validate before drawing.

JavaScript
const rows = parseInt(prompt("Enter number of rows:"), 10);
let m = 0;

if (!Number.isFinite(rows) || rows < 1) {
  console.log("Please enter a positive integer.");
} else {
  for (let r = 1; r <= rows; r++) {
    let line = " ".repeat(4 * (rows - r));
    for (let k = 0; k < 2 * r - 1; k++) {
      m += 1;
      line += String(m * m).padStart(4, " ");
    }
    console.log(line);
  }
}
Try It Yourself

How It Works

1. Prompt and validate. Use parseInt and reject non-positive values.

2. Same pyramid core. Only the source of rows changes — pads, widths, and m match Example 1.

3. Entering 3 stops early. Nine squares total (3²), ending at 81.

Example 3 — Left-Aligned

Same squares and padStart, without leading-space centering.

JavaScript
const rows = 5;
let m = 0;

for (let r = 1; r <= rows; r++) {
  let line = "";
  for (let k = 0; k < 2 * r - 1; k++) {
    m += 1;
    line += String(m * m).padStart(4, " ");
  }
  console.log(line);
}
Try It Yourself

How It Works

1. Drop the left pad. Start each line as "" instead of repeating spaces.

2. Keep column width. padStart(4) still lines up multi-digit squares.

3. Same square sequence. Only the centering changes — useful for comparing with Example 1.

Edge Cases & Pitfalls

Check these before calling the solution done.

Reset m

Keep m outside the outer loop

Resetting m each row restarts at 1 every time and breaks the continuous square sequence.

padStart

Match pad width to cell width

Leading spaces use 4 * (rows - r) because each cell is 4 columns. A different cell width needs a matching pad formula.

log early

Call console.log only after the row is built

Logging inside the inner loop prints one square per line.

Bad input

Validate parseInt

Check Number.isFinite(rows) and require rows >= 1 before the loops.

Time and Space Complexity

ProgramTimeExtra space
Centered (Examples 1–2)O(n²)O(n) per row string
Left-aligned (Example 3)O(n²)O(n) per row string

Squares appended are 1 + 3 + 5 + … + (2n − 1) = n² — quadratic in n. Each row builds a temporary string proportional to the row width.

Key Takeaways

  • Rule: bump m, append m², use odd widths 2*r - 1.
  • Center: leading spaces of length 4 * (rows - r) match padStart(4).
  • Break the row: call console.log(line) only after pads and squares finish.
  • Complexity: O(n²) time — total squares = n².

One line: keep a continuous counter, append each square in odd-width rows, and pad left for centering.

Frequently Asked Questions

A centered pyramid of perfect squares: row 1 appends 1 (1²), row 2 appends 4 9 16 (2², 3², 4²), and so on.
The inner loop runs 2 * r - 1 times per row r — that produces odd counts: 1, 3, 5, 7, 9 squares.
Leading spaces via " ".repeat(4 * (rows - r)) shift narrow rows right so the pyramid stays centered in fixed-width columns.
m starts at 0 and increments before each append. Each value appended is m * m — the next perfect square in sequence.
Fixed-width columns keep the pyramid aligned as squares grow from 1 to 625. Without it, columns drift apart.
line += appends on the same row. console.log(line) ends the row after pads and squares finish.
Program 40 alternates 1 and 0 with shrinking rows. Program 41 appends perfect squares in a centered pyramid with growing odd-width rows.
O(n²) for n rows — total appends are 1+3+5+…+(2n-1) = n².

Did you know?

Each appended value is m² from a running counter m. Row widths are odd (1, 3, 5, 7, 9) — total appends for n rows = n².

Next: Hollow Square of 1s

Continue with the next pattern in the JavaScript number-pattern series.

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