Perfect Square Spiral Pattern in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Spiral matrix

What You’ll Learn

How to generate a 10×10 spiral matrix from 1 to 100 and print it as a number pattern.

The same technique works for any \(N \times N\) size by changing one variable.

⭐ Pattern Output

Expected output for a 10×10 perfect square spiral:

Output
1   2   3   4   5   6   7   8   9  10
36  37  38  39  40  41  42  43  44  11
35  64  65  66  67  68  69  70  45  12
34  63  84  85  86  87  88  71  46  13
33  62  83  96  97  98  89  72  47  14
32  61  82  95  100 99  90  73  48  15
31  60  81  94  93  92  91  74  49  16
30  59  80  79  78  77  76  75  50  17
29  58  57  56  55  54  53  52  51  18
28  27  26  25  24  23  22  21  20  19
1

Complete JavaScript Program

Fill the matrix in 4 directions (top row, right column, bottom row, left column) and then shrink the boundaries.

JavaScript
const size = 10;
const a = Array.from({ length: size }, () => Array(size).fill(0));

let top = 0, bottom = size - 1;
let left = 0, right = size - 1;
let n = 1;

while (top <= bottom && left <= right) {
  for (let j = left; j <= right; j++) a[top][j] = n++;
  top++;

  for (let i = top; i <= bottom; i++) a[i][right] = n++;
  right--;

  for (let j = right; j >= left; j--) a[bottom][j] = n++;
  bottom--;

  for (let i = bottom; i >= top; i--) a[i][left] = n++;
  left++;
}

for (let i = 0; i < size; i++) {
  const line = a[i].map(v => String(v).padStart(3, " ")).join("  ");
  console.log(line);
}

🧠 How It Works

1

Create a size×size array

Initialize a matrix filled with 0.

Setup
2

Maintain four boundaries

top, bottom, left, right describe the current layer.

Bounds
3

Fill 4 sides clockwise

Top row → right column → bottom row → left column.

Spiral
4

Shrink boundaries

After each layer, move inward by adjusting the boundaries.

Repeat
=

Layer-by-layer spiral

The same idea scales to any size.

2

Variation — Browser Grid Version

Render the spiral in the browser using fixed-width cells:

HTML
<!DOCTYPE html>
<html>
<head>
  <style>
    .cell { display:inline-block; width:2.6em; text-align:right; }
  </style>
</head>
<body>
<script>
var size = 10;
var a = Array.from({ length: size }, function () { return Array(size).fill(0); });

var top = 0, bottom = size - 1, left = 0, right = size - 1;
var n = 1;

while (top <= bottom && left <= right) {
  for (var j = left; j <= right; j++) a[top][j] = n++;
  top++;
  for (var i = top; i <= bottom; i++) a[i][right] = n++;
  right--;
  for (var j2 = right; j2 >= left; j2--) a[bottom][j2] = n++;
  bottom--;
  for (var i2 = bottom; i2 >= top; i2--) a[i2][left] = n++;
  left++;
}

for (var r = 0; r < size; r++) {
  for (var c = 0; c < size; c++) {
    document.write('<span class="cell">' + a[r][c] + '</span>');
  }
  document.write("<br>");
}
</script>
</body>
</html>

💡 Tips for Enhancement

Try These

  • Change size to 5, 7, 12, etc. (make sure to adjust padding width)
  • Start counting from a different number (e.g., 101)
  • Fill anti-clockwise by changing the order of sides
  • Store and print as a table for cleaner HTML

Avoid

  • Forgetting to update boundaries (will overwrite values or loop forever)
  • Printing without alignment (grid will look uneven)
  • Using document.write in production apps (fine for demos)

Key Takeaways

1

Spirals are easiest with top/bottom/left/right boundaries.

2

Fill 4 sides per layer, then shrink the boundaries.

3

Use padStart or fixed-width spans for clean alignment.

4

The same logic generalizes to any \(N \times N\) size.

❓ Frequently Asked Questions

Because we fill 1..100 in order while moving inward, the final remaining cell (center) receives the last value.
The boundary loop works for both. Odd sizes end with one center cell; even sizes end with a 2×2 center area filled normally.
Yes, but the algorithm changes. This tutorial uses the simpler outer-to-inner boundary method.
A matrix makes it easy to fill values in spiral order and then print row-by-row with consistent formatting.

Next: Star Pattern Programs

You’ve completed the number patterns series—continue with JavaScript star patterns.

Star Patterns →
Did you know?

Spiral matrices are common interview questions because they test boundary conditions and loop control.

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