JavaScript Hollow Square Pattern (Border of 1s)

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

What Is This Pattern?

A hollow square of 1s fills only the border of an n×n grid — first/last row and first/last column get 1; interior cells stay blank.

Remember
Rule: if border → "1 "; else → "  "

1 1 1 1 1
1       1
1       1
1       1
1 1 1 1 1     ← n = 5

Unlike Program 41 (square pyramid), this pattern visits every cell and decides with a simple border check — total cells for size n is n².

How to Solve It

Loop rows and columns from 1 to n. Append "1 " on the border; otherwise append two spaces. End each row with console.log.

MethodIdeaBest for
Border ifi === 1 || i === n || j === 1 || j === nClassic hollow square
Other charSame check; append "* " instead of "1 "Star-border demos

Pseudocode

Pseudocode
for i from 1 to n:
    line = ""
    for j from 1 to n:
        if i is 1 or i is n or j is 1 or j is n:
            append "1 "
        else:
            append "  "
    print line

Cheat sheet

GoalPattern
Outer (rows)for (let i = 1; i <= n; i++)
Inner (cols)for (let j = 1; j <= n; j++)
Border testi === 1 || i === n || j === 1 || j === n
Border cellline += "1 ";
Interior cellline += " ";
End the rowconsole.log(line);

Printing Numbers vs Starting a New Line

APIEffectUse for
line += …Stays on the same rowEach cell ("1 " or " ")
console.log(line)Ends the current rowAfter all columns in the row

Append without a newline, then end the row once.

Live Preview

Change the square size and the hollow border updates instantly.

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

Live result n = 5 · 25 cells
1 1 1 1 1 
1       1 
1       1 
1       1 
1 1 1 1 1 

Worked Walkthrough

Trace three rows when n = 5 — watch which cells get 1 vs spaces.

Row iBorder cellsInteriorPrinted row
1all j (top)none1 1 1 1 1
2j=1, j=5j=2..4 spaces1 1
5all j (bottom)none1 1 1 1 1

Middle rows only light the left and right edges; top and bottom fill every column.

JavaScript Programs

Three complete programs: fixed n = 5, prompt input, and an asterisk border. Use View Output for samples, or Try It Yourself to edit and run live.

Example 1 — Fixed n = 5

Hard-coded size — border check, "1 " on edges, two spaces inside.

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

1. Walk the grid. Outer loop is rows; inner loop is columns — both run 1 to n.

2. Test the border. i === 1 || i === n || j === 1 || j === n marks every edge cell.

3. Keep columns aligned. Border cells append "1 "; interior cells append " " so spacing matches.

Example 2 — User Input Size

Read n with prompt and validate before drawing.

JavaScript
const n = parseInt(prompt("Enter square size (n >= 2):"), 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

1. Prompt and validate. Use parseInt and require n >= 2 for a meaningful hollow frame.

2. Same border core. Only the source of n changes — the if condition matches Example 1.

3. Entering 4. A 4×4 frame: full top/bottom rows, sides only in the middle.

Example 3 — Asterisk Border

Same hollow frame; border cells append "* " 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

1. Same geometry. The border test is unchanged — only the printed character differs.

2. Swap the glyph. Use "* " (or "# ") in the if branch; keep " " for the interior.

3. Still align columns. One character plus one space per cell keeps the frame neat.

Edge Cases & Pitfalls

Check these before calling the solution done.

Spacing

Match interior width to "1 "

Interior cells must append two spaces (" "), not one — otherwise columns drift.

n vs 5

Use n in the border test

Hard-coding i === 5 breaks when size changes. Always compare against n.

log early

Call console.log only after the row is built

Logging inside the inner loop prints one cell per line.

Bad input

Validate parseInt

Check Number.isFinite(n) and require n >= 2 before the loops.

Time and Space Complexity

ProgramTimeExtra space
Hollow 1s (Examples 1–2)O(n²)O(n) per row string
Asterisk border (Example 3)O(n²)O(n) per row string

Every cell is visited once — n × n checks — so time is quadratic in n. Each row builds a temporary string proportional to the width.

Key Takeaways

  • Rule: print 1 on the border; leave the interior blank.
  • Test: i === 1 || i === n || j === 1 || j === n.
  • Break the row: call console.log(line) only after all columns finish.
  • Complexity: O(n²) time — visit every cell once.

One line: nest two loops over n, append "1 " on the border and two spaces inside, then log each row.

Frequently Asked Questions

An n×n hollow square: 1 on every border cell (first/last row and first/last column), spaces inside.
Check i === 1 || i === n || j === 1 || j === n. If true, append "1 "; otherwise append two spaces.
Each border cell uses "1 " (digit plus space). Interior cells use " " so columns stay aligned.
Size 2 is a thin frame. Size 1 prints a single 1 with no hollow interior.
line += appends on the same row. console.log(line) ends the row after all columns finish.
Program 41 appends a centered pyramid of perfect squares. Program 42 appends a hollow square 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.

Did you know?

Append 1 when i === 1, i === n, j === 1, or j === n; otherwise append two spaces. An n × n grid visits n² cells.

Next: Right-Aligned Number Triangle

Continue with the next pattern 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