Hollow Square of 1s in JavaScript

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

What You’ll Learn

The hollow square of 1s prints a 5×5 border frame — 1 1 1 1 1 on top and bottom, 1 on the sides, spaces inside — a natural step after Program 41’s square pyramid. This tutorial covers nested loops, border conditions, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Border only

Print 1 on the first/last row and first/last column — leave interior cells as spaces.

Outer Loop

Rows (i)

for (let i = 1; i <= n; i++) walks each row of the grid.

Inner Loop

Columns (j)

for (let j = 1; j <= n; j++) visits every column in the current row.

Border check

if condition

i === 1 || i === n || j === 1 || j === n — append "1 " on the edge, two spaces inside.

Live Preview

3–9 size

Pick a square size and draw the hollow border in the browser.

O(n²)

Complexity

Every cell in an n×n grid is visited once — total checks = .

Introduction

A hollow square of 1s prints 1 only on the border of an n×n grid and spaces everywhere else. With n = 5, the output is a 5×5 frame of ones with a hollow center.

In JavaScript nested loops walk every cell (i, j), an if checks whether the cell is on the border, and line += builds each row before console.log(line).

Why it matters?

It combines nested loops with a boundary condition — a key step after Program 41’s formatted pyramid.

Key Highlights

Border rule

First/last row or column prints 1.

Grid traversal

Nested loops visit every (i, j) cell.

vs Program 41

Program 41 prints perfect squares; Program 42 prints a hollow frame.

Series Foundation

Follow Program 41; continue to Program 43 (right-aligned triangle) next.

In short: for each (i, j) in an n×n grid, append 1 on the border else two spaces, then console.log(line) each row.

📝 Problem & Approach

Given a grid size n (e.g. 5), print a hollow square border of 1s using nested loops and a border condition.

JavaScript
// n = 5 (conceptual shape)
// 1 1 1 1 1
// 1       1
// 1       1
// 1       1
// 1 1 1 1 1

Inputs & Outputs

ItemTypeDescription
nnumberSide length of the square grid — both loops run 1..n.
inumberOuter loop — row index from 1 to n.
jnumberInner loop — column index from 1 to n.

Minimal workflow

Pseudocode
for i from 1 to n:
    for j from 1 to n:
        if i is border or j is border:
            print 1
        else:
            print space
    print newline

Approach comparison

ApproachIdeaBest for
Border condition1 1 1 1 1 frameLearning and interviews
User-input sizeparseInt(prompt(), 10)Flexible console programs
Custom border charPrint * instead of 1Visual variety

⚡ Quick Reference

GoalPattern
Walk rowsfor (let i = 1; i <= n; i++)
Walk columnsfor (let j = 1; j <= n; j++)
Border checkif (i === 1 || i === n || j === 1 || j === n)
Append borderline += "1 "
Append interiorline += " "
End the rowconsole.log(line)
Program 41 contrastPerfect-square pyramid — not a hollow grid

📋 Fixed Size vs User Input vs Asterisk Border

Same hollow square — different ways to control size and border character.

Outer loop
i = 1..n

Row index

Inner loop
j = 1..n

Column index

Border
i/j === 1 || n

Edge cells append 1

Learning tip
line +=

Keeps grid aligned

Context

When This Pattern Shows Up

Reach for this pattern when teaching boundary conditions with nested loops on a 2D grid.

  1. After Program 41

    Natural follow-up — boundary conditions on a grid instead of formatted square pyramids.

  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 square size.

  4. Gateway to variants

    Swap 1 for * on the border — 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 square size between 3 and 9 and draw the hollow border in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed size, prompt() input, and asterisk border. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print a 5×5 hollow square border with nested loops and a border condition.

Example 1 — Fixed n = 5

Hard-coded grid size — ideal for first demos and screenshots.

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let line = "";
  for (let j = 1; j <= n; j++) {
    if (i === 1 || i === n || j === 1 || j === n) {
      line += "1 ";
    } else {
      line += "  ";
    }
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 1 or i = 5, every cell is on the border — all 1s. When i = 3 and j = 3, neither row nor column is on the edge — prints spaces.

📈 User Input

Read the square size with prompt() instead of hard-coding 5.

Example 2 — User Input Size

Read n with prompt() and validate n ≥ 2 (check with Number.isFinite in real apps).

JavaScript
const nInput = prompt("Enter the size (n >= 2):");
const n = parseInt(nInput, 10);

if (!Number.isFinite(n) || n < 2) {
  console.log("Please enter an integer n >= 2.");
} else {
  for (let i = 1; i <= n; i++) {
    let line = "";
    for (let j = 1; j <= n; j++) {
      if (i === 1 || i === n || j === 1 || j === n) {
        line += "1 ";
      } else {
        line += "  ";
      }
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

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

⚡ Custom Border

Swap 1 for * on the border — same condition, different character.

Example 3 — Asterisk Border

Keep n = 5 but print * on the border instead of 1.

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let line = "";
  for (let j = 1; j <= n; j++) {
    if (i === 1 || i === n || j === 1 || j === n) {
      line += "* ";
    } else {
      line += "  ";
    }
  }
  console.log(line);
}
Try it Yourself

How It Works

Only the appended character changes — "* " instead of "1 " in the if branch. Loop bounds and border check stay the same as Example 1.

🧠 How the Algorithm Prints the Grid

1

Set up

No imports needed. Set n = 5 and loop variables i, j.

Setup
2

Outer loop (rows)

for (let i = 1; i <= n; i++) — walks each row of the grid.

Row
3

Inner loop (columns)

for (let j = 1; j <= n; j++) — visits every column in the current row.

Column
4

Border check

if (i === 1 || i === n || j === 1 || j === n) — append "1 " on the edge, two spaces inside.

Condition
5

New line

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

Break
=

Hollow square frame complete

Every cell in an n×n grid is visited — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — n = 5, row i = 3

Trace row 3 cell by cell — which cells print 1 and which print spaces.

jOn border?Prints
1Yes (j == 1)1
2No
3No
4No
5Yes (j == n)1

Border cells per row = 4n - 4 for n ≥ 2 — total grid visits = .

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: swap 1 for * on the border — see Example 3.

2. Pattern Series Base

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

Example: continue to Program 43 for a right-aligned number triangle.

3. Console Formatting Drills

Practice line += vs console.log(line) without complex math.

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

4. Hollow rectangle

Use separate rows and cols with the same border check.

Example: change both loop bounds and border conditions.

5. Complexity Intuition

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

Example: count border cells for n = 5 — total is 16 (4n - 4).

6. Input Validation Labs

Pair the pattern with Number.isFinite and prompt() validation.

Example: reject n < 2 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 (i, j) on paper for n = 3 before coding the full n = 5 demo.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Keep Cell Width Consistent

    Border cells use line += "1 "; interior uses line += " " — same width keeps columns aligned.

  2. 2. Validate with Number.isFinite

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

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

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

  4. 4. One Border Condition

    i === 1 || i === n || j === 1 || j === n covers all four edges in one test.

  5. 5. Dry-Run n = 3

    Trace i = 1, 2, 3 and mark border cells before coding the full n = 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 hollow square border patterns.

  1. 1. Newline Inside the Inner Loop

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

    → Use line += "1 " or line += " " per cell; console.log(line) only after the inner loop.

  2. 2. Hard-Coded Size in Condition

    Using i == 5 in the check breaks when n changes to 7 or 10.

    → Always use the n variable: i === n || j === n.

  3. 3. Mismatched Cell Width

    Border prints "1 " but interior prints a single space — columns drift apart.

    → Use two spaces for interior: line += " " to match "1 " width.

  4. 4. Size Too Small

    n = 1 prints a single 1 with no hollow interior; n = 2 is the thinnest frame.

    → Validate n ≥ 2 for interactive programs expecting a hollow square.

  5. 5. Bare parseInt(prompt())

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

    → Check Number.isFinite(n) and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Size = 1

Output is just 1 on one line — no hollow interior.

n = 0

Empty pattern

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

Negative

n < 0

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

n = 2

Size = 2

Thinnest hollow frame — four border cells forming a square ring.

Bad input

Non-numeric input

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

Large n

Large grid size

Each cell visited once — total work grows as for an n × n grid.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Square pyramid

  • Review Program 41’s m*m pyramid
  • Compare with Program 41

2. Filled square

  • Print 1 in every cell — no border check
  • Same nested loops, no else branch

3. Next in series

  • Continue with Program 43
  • Build on grid boundary logic

4. Asterisk border

  • Use "*" instead of "1"
  • Same condition, different character

Notes

  • Border rule. Append "1 " when i === 1 || i === n || j === 1 || j === n; else append " ".
  • Build each row with line +=, then console.log(line) once per row.
  • Validate n ≥ 2 for interactive programs; n = 1 should print a single 1.
  • An n × n grid has cells — border cells = 4*n - 4 for n ≥ 2.

Quick Takeaway: nested loops over i, j, border check appends "1 ", else " ", 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 hollow square border is a compact nested-loop lesson: visit every cell in an n × n grid and use a border condition to print 1 or spaces. Master the fixed-n version, then try user input and a custom border character.

Practice the three examples above, then continue to Program 43 for the next pattern in the series.

Border = first/last row or column — keep cell width consistent ("1 " vs " ") and validate n when reading input.

💡 Best Practices

✅ Do

  • Use for (let i = 1; i <= n; i++) and for (let j = 1; j <= n; j++)
  • Border: if (i === 1 || i === n || j === 1 || j === n)
  • Append "1 " on border, " " inside — same cell width
  • Validate n ≥ 2 for interactive programs
  • Check Number.isFinite(n) after parseInt(prompt())

❌ Don’t

  • Call console.log(line) inside the inner cell loop
  • Hard-code 5 in the border condition
  • Use single space for interior when border uses two chars
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this hollow square border

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Rows i = 1..n

Code
03

Inner loop

Columns j = 1..n

Code
04

Condition

i/j on edge

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A hollow square appends characters only on the border (first/last row and first/last column) and leaves the inside blank with spaces.
It checks if i is 1 or n, or if j is 1 or n. If any condition is true, it appends 1; otherwise it appends spaces.
Use an n variable and loop from 1 to n for both i and j. Update the border check to use n instead of 5 — see Example 2.
Each border cell uses "1 " (digit plus space). Interior cells use " " so columns stay aligned in the console.
Size 2 gives a thin border frame. Size 1 appends a single 1 with no hollow interior.
Program 41 appends a centered pyramid of perfect squares. Program 42 appends a hollow square grid using border conditions.
Replace "1" with "*" or "#" in the if branch — see Example 3.
O(n²) for an n×n grid because each cell is visited once.
Use parseInt with Number.isFinite and validate n >= 2 for a meaningful hollow frame.

Did you Know? 🔊

Append 1 when i === 1, i === n, j === 1, or j === n; otherwise append two spaces. A n × n grid visits cells — total appends = .

Continue to Program 43

Move on to the right-aligned number triangle in the JavaScript number-pattern series.

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