Hollow Square Border of 1s in JavaScript

What You’ll Learn
How to print a hollow square border using 1 on the edges and spaces inside.
This teaches a common pattern-printing trick: decide output based on whether a cell is on the border.
⭐ Pattern Output
For size = 5, the pattern looks like this:
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 1Complete JavaScript Program
If the current cell is on the first/last row or first/last column, print 1. Otherwise print spacing.
const size = 5;
for (let i = 1; i <= size; i++) {
let line = "";
for (let j = 1; j <= size; j++) {
if (i === 1 || i === size || j === 1 || j === size) {
line += "1 ";
} else {
line += " ";
}
}
console.log(line.trimEnd());
}🧠 How It Works
Set the grid size
size = 5 means we print a 5×5 grid.
Outer loop controls rows
i goes from 1..size and represents the current row.
Inner loop controls columns
j goes from 1..size and represents the current column.
Border condition prints 1
When i or j is on an edge (1 or size), we print 1; otherwise we print spacing.
Hollow inside
Only border cells print 1; all inner cells are blank.
Variation — Browser (document.write) Version
Print the hollow square in an HTML page using document.write and for spaces:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 5; j++) {
if (i == 1 || i == 5 || j == 1 || j == 5)
document.write("1 ");
else
document.write(" ");
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
sizeto print a bigger hollow square - Replace 1 with another digit or symbol
- Fill the inside with another value (like 0) instead of spaces
- Use CSS monospace fonts to keep spacing consistent
Avoid
- Using normal spaces in HTML (they can collapse); prefer
- Forgetting the edge condition (you’ll fill the whole square)
- Mixing inconsistent spacing (output alignment may look off)
Key Takeaways
Border patterns are made with simple edge checks on i and j.
Only the first/last row and first/last column print 1.
Everything else prints spaces to create a hollow interior.
The same idea applies to hollow rectangles and frames.
❓ Frequently Asked Questions
j == 1 and j == size detect the left and right borders."0 " instead of spaces.Explore More JavaScript Number Patterns!
Border-based patterns are a great way to practice conditional logic inside grids.
Hollow shapes are usually easier than they look: you only need to identify the boundary cells. Everything else is “inside” and can be spaces or another fill.
12 people found this page helpful
