Square Numbers Pyramid in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Math

What You’ll Learn

The square number pyramid prints 1, then 4 9 16, then 25 36 49 64 81, … — a natural step after Program 40’s alternating 1/0 pattern. This tutorial covers odd-length rows, indentation centering, a running counter m, padStart(4) formatting, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

m² per value

Row 1 prints 1, row 2 prints 4 9 16, row 3 prints five squares — each value is the next perfect square.

Outer Loop

r = 1..rows

for (let r = 1; r <= rows; r++) — each row appends 2*r - 1 perfect squares.

Leading Spaces

Center rows

" ".repeat(4 * (rows - r)) indents narrow rows so the pyramid stays centered.

Counter m

Running sequence

Increment m, then append String(m*m).padStart(4, " ") — squares progress 1, 4, 9, 16, 25, … continuously.

Live Preview

2–5 levels

Pick a level count and draw the square-number pyramid in the browser.

O(n²)

Complexity

Total square prints = for n rows; extra memory stays O(1).

Introduction

A square number pyramid prints perfect squares in centered rows of odd length — 1, then 3, then 5 squares per row. With rows = 5, the output starts with 1, then 4 9 16, then 25 36 49 64 81, and continues.

In JavaScript the outer loop runs r = 1..rows, leading spaces center each row, and the inner loop appends String(m*m).padStart(4, " ") while incrementing m.

Why it matters?

It combines nested loops with math and formatted output — a key step after Program 40’s alternating rows.

Key Highlights

Odd row widths

Each row prints 2r - 1 squares.

Centering

Leading spaces shift narrow rows right.

vs Program 40

Program 40 alternates 1/0; Program 41 prints perfect squares.

Series Foundation

Follow Program 40; continue to Program 42 (hollow square) next.

In short: outer r = 1..rows, indent spaces, inner append String(m*m).padStart(4, " "), increment m, then console.log(line).

📝 Problem & Approach

Given a row count rows (e.g. 5), print a centered pyramid of perfect squares using a running counter m and fixed-width columns.

JavaScript
// rows = 5 (conceptual shape)
//                   1
//               4   9  16
//          25  36  49  64  81
// ...

Inputs & Outputs

ItemTypeDescription
rowsnumberNumber of pyramid rows — outer loop runs r = 1..rows.
rnumberOuter loop — row index; inner loop prints 2*r - 1 squares.
mnumberRunning counter — each printed value is m*m.

Minimal workflow

Pseudocode
m = 0
for r from 1 to rows:
    print leading spaces
    for _ from 1 to (2*r - 1):
        m++
        print m*m with fixed width
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + counter1, 4 9 16, …Learning and interviews
User-input rowsparseInt(prompt(), 10)Flexible console programs
Left-aligned variantSkip leading spacesEasier tracing on paper

⚡ Quick Reference

GoalPattern
Walk rowsfor (let r = 1; r <= rows; r++)
Center rowline = " ".repeat(4 * (rows - r))
Append squaresm += 1; line += String(m*m).padStart(4, " ")
Squares per rowfor (let k = 0; k < 2 * r - 1; k++)
End the rowconsole.log(line)
Wider columnspadStart(6, " ") when squares exceed 999
Program 40 contrastAlternating 1/0 with shrinking rows — not perfect squares

📋 Fixed Rows vs User Input vs Left-Aligned

Same square-number pyramid — different ways to control rows and alignment.

Outer loop
r = 1..rows

Each row prints 2r-1 squares

Counter
m += 1; m*m

Continuous perfect squares

Centering
4 * (rows - r)

Leading spaces per row

Learning tip
padStart(4)

Keeps columns aligned

Context

When This Pattern Shows Up

Reach for this pattern when teaching formatted output, centering, and running counters with nested loops.

  1. After Program 40

    Natural follow-up — perfect squares in a centered pyramid instead of alternating binary digits.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with prompt() for a flexible row count.

  4. Gateway to variants

    Print cubes with m**3 or skip centering for a left-aligned pyramid — see Example 3.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a level count between 2 and 5 and draw the square-number pyramid in the browser.

Try 2, 3, or 4. Max up to 5 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed rows, prompt() input, and a left-aligned variant. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print five rows of the square-number pyramid with nested loops and formatted output.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

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

When r = 1, one square prints — 1. When r = 2, three squares print — 4 9 16 (from m = 2, 3, 4). Leading spaces shift narrow rows right so the pyramid stays centered.

📈 User Input

Read the row count with prompt() instead of hard-coding 5.

Example 2 — User Input

Read rows with prompt() and parseInt() (check with Number.isFinite in real apps).

JavaScript
const rowsInput = prompt("Enter number of rows:");
const rows = parseInt(rowsInput, 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

Same square-filling core as Example 1; only the source of rows changes from a literal to user input. Non-numeric input yields NaN with bare parseInt() — use Number.isFinite for safer labs.

⚡ Left-Aligned

Skip the leading-space prefix to draw squares flush left — easier to trace on paper.

Example 3 — Left-Aligned Pyramid

Same squares and counter — no leading spaces.

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

Only the leading-space prefix is removed — m*m and padStart(4) formatting stay the same as Example 1. Rows grow wider to the right without centering.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed. Set rows = 5, m = 0, and loop variable r.

Setup
2

Outer loop walks rows

for (let r = 1; r <= rows; r++) — each row appends 2*r - 1 perfect squares.

Row
3

Leading spaces

line = " ".repeat(4 * (rows - r)) — indents narrow rows so the pyramid stays centered.

Center
4

Print squares

m += 1; line += String(m*m).padStart(4, " ") — fixed-width perfect squares in sequence.

Squares
5

New line

console.log(line) ends the row after the inner loop finishes.

Break
=

Square-number pyramid complete

Total prints for 5 rows = 1+3+5+7+9 = 25O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of r, indent count, square count, m range, and row output.

rSpacesSquaresm rangeValues
116111
21232–44 9 16
3855–925 36 49 64 81
44710–16100 121 144 … 256
50917–25289 324 … 625

Squares per row = 2*r - 1 — total prints = 1+3+5+7+9 = 25 = 5² for 5 rows.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change padStart(4) to padStart(6) when squares exceed 999.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: continue to Program 42 for a hollow square of 1s.

3. Console Formatting Drills

Practice print vs row newline without complex math.

Example: put console.log(line) inside the inner loop by mistake.

4. Spaced Output

Add spaces between digits once the two-loop structure works.

Example: use padStart(6, " ") for larger pyramids.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed squares for 5 rows — total is 25 ().

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace r, m, and indent count on paper for rows = 3 before coding the full demo.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Use Fixed-Width Formatting

    String(m*m).padStart(4, " ") keeps columns aligned — widen to padStart(6) when squares exceed 999.

  2. 2. Validate with Number.isFinite

    Use Number.isFinite(rows) so bad input does not crash when converting rows.

  3. 3. Keep console.log Outside the Inner Loop

    Only call console.log(line) after the inner loop finishes the row.

  4. 4. Separate Spacing from Values

    Print leading spaces before the inner loop — keep the square-print logic inside the inner loop only.

  5. 5. Dry-Run rows = 3

    Trace r = 1, 2, 3 and watch m grow before coding the full rows = 5 demo.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put console.log(line) inside the inner loop.

Common Pitfalls

Mistakes that commonly break square-number pyramids.

  1. 1. Newline Inside the Inner Loop

    Each square lands on its own line — you get a column, not a pyramid.

    → Use line += String(m*m).padStart(4, " ") for squares; console.log(line) only after the inner loop.

  2. 2. Forgetting Fixed Width

    Appending bare m*m without padStart(4) makes columns drift as numbers get wider.

    → Always use String(m*m).padStart(4, " ") (or wider) for aligned columns.

  3. 3. Resetting m Each Row

    m = 0 inside the outer loop restarts squares on every row instead of continuing the sequence.

    → Initialize m = 0 once before the outer loop.

  4. 4. Forgetting the Row Break

    Omitting console.log(line) glues every digit onto one endless line.

    → Always end the row after the inner loop.

  5. 5. Bare parseInt(prompt())

    Letters or empty input yield NaN with bare parseInt().

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single square row

Output is just 1 on one centered line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Smallest pyramid

Two rows: 1 then 4 9 16.

Bad input

Non-numeric input

Bare parseInt(prompt()) yields NaN on bad input — use Number.isFinite first.

Large rows

Large row count

Each row prints 2*r - 1 squares — total work grows as .

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Alternating 1/0 triangle

  • Review Program 40
  • Alternating 1/0 with shrinking rows

2. Hollow square of 1s

  • Continue with Program 42
  • Boundary check with nested loops

3. Cube pyramid

  • Replace m*m with m**3
  • Same loops, different math

4. Left-aligned variant

  • Remove leading-space print
  • Same counter, no centering

Notes

  • Square rule. Outer loop: r = 1..rows. Inner loop: for (let k = 0; k < 2*r - 1; k++). Value: m*m with padStart(4) width.
  • " ".repeat(4 * (rows - r)) centers rows; console.log(line) advances to the next line.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Total squares for n rows = — the sum of the first n odd numbers.

Quick Takeaway: outer loop r = 1..rows, indent spaces, inner for (let k = 0; k < 2*r - 1; k++) with String(m*m).padStart(4, " "), then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The square number pyramid is a compact nested-loop lesson: a running counter m prints perfect squares while leading spaces keep rows centered. Master the fixed-rows version, then try user input and the left-aligned variant.

Practice the three examples above, then continue to Program 42 for the hollow square of 1s.

Each value is — keep String(m*m).padStart(4, " ") for aligned columns and console.log(line) for the row break.

💡 Best Practices

✅ Do

  • Use for (let r = 1; r <= rows; r++) in the outer loop
  • Inner: for (let k = 0; k < 2 * r - 1; k++) appends odd counts per row
  • Use String(m*m).padStart(4, " ") for aligned columns and console.log(line) after each row
  • Center with line = " ".repeat(4 * (rows - r)) before the inner loop
  • Check Number.isFinite(rows) after parseInt(prompt())

❌ Don’t

  • Call console.log(line) inside the inner square loop
  • Reset m inside the outer loop (breaks the sequence)
  • Skip fixed-width formatting (columns drift)
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this square-number pyramid

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

for (let r = 1; r <= rows; r++)

Code
03

Inner loop

for (let k = 0; k < 2*r - 1; k++)

Code
04

Centering

4 * (rows - r) spaces

Align
O 05

Complexity

O(n²) time

Analysis

❓ 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.
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.
Increase rows — see Example 2 for reading levels with prompt().
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².
Yes — remove the leading-space prefix to get a left-aligned pyramid. See Example 3.

Did you Know? 🔊

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

Continue to Program 42

Move on to the hollow square of 1s 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