Zero + Star Cross (X + Middle Column) in JavaScript

What You’ll Learn
How to print a grid pattern using 0 and * in JavaScript, where stars draw an X and a fixed middle column.
This is a great example of combining multiple conditions inside nested loops.
⭐ Pattern Output
For rows = 4 and cols = 9, the pattern looks like this:
*000*000*
0*00*00*0
00*0*0*00
000***000Complete JavaScript Program
If a cell is on either diagonal or on the middle column, we print *. Otherwise, we print 0.
const rows = 4;
const cols = 9;
const middle = (cols + 1) / 2; // 5 when cols = 9
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= cols; j++) {
if (i === j || j === middle || i === cols + 1 - j) {
line += "*";
} else {
line += "0";
}
}
console.log(line);
}🧠 How It Works
Set rows and columns
rows = 4 and cols = 9 define a 4×9 grid.
Find the middle column
middle = (cols + 1) / 2 gives 5 when cols is 9.
Scan each cell (i, j)
The nested loop checks every position in the grid and decides what to print.
Star condition (3 rules)
Print * if i === j (main diagonal), or i === cols + 1 - j (other diagonal), or j === middle (middle column).
X + middle column
Combining the diagonals with the center column produces the final cross pattern.
Variation — Browser (document.write) Version
Same logic, but printed in the browser using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
var rows = 4;
var cols = 9;
var middle = (cols + 1) / 2;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= cols; j++) {
if (i == j || j == middle || i == cols + 1 - j)
document.write("*");
else
document.write("0");
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
rowsandcolsto draw a bigger X - Keep
colsodd so the middle column is a single clean line - Replace
0with.or a space for a lighter background - Remove the middle-column condition to print only the X
Avoid
- Using an even number of columns if you need a single center column
- Hardcoding numbers without documenting what they represent (rows/cols/center)
- Mixing 0-based and 1-based formulas without adjusting diagonal conditions
Key Takeaways
Nested loops scan a grid row by row and column by column.
Multiple conditions can be combined with || to create shapes.
For odd columns, (cols + 1) / 2 gives the center column.
Patterns like X, plus, and borders are just coordinate rules.
❓ Frequently Asked Questions
i + j = cols + 1, which is equivalent to i === cols + 1 - j.rows equal to cols (and keep cols odd if you want the middle column).j === middle as the star condition.if and else blocks.Explore More JavaScript Number Patterns!
Once you can think in grid coordinates, you can create borders, diagonals, and complex logos with simple rules.
Many pattern problems become easy once you treat output as a grid of coordinates \((i, j)\) and write rules for which cells should be special.
12 people found this page helpful
