Mirrored Diagonal Numbers Pattern

What You’ll Learn
How to print a pattern where each row prints its index on the left diagonal and again on the right mirrored diagonal.
This is a good exercise for understanding coordinates \((row, column)\) and spacing.
⭐ Pattern Output
For n = 5, the pattern looks like this:
1 1
2 2
3 3
4 4
5Complete JavaScript Program
We scan across a row and print the row number when the column matches a diagonal position. Otherwise we print spaces. (Use a monospace font for perfect alignment.)
const n = 5;
const width = 2 * n - 1;
for (let i = 1; i <= n; i++) {
let line = "";
for (let col = 1; col <= width; col++) {
const leftDiag = col === i;
const rightDiag = col === width - i + 1;
line += leftDiag || rightDiag ? String(i) : " ";
}
console.log(line.trimEnd());
}🧠 How It Works
Set n and width
We use width = 2*n - 1 so there is room for two diagonals.
Row loop (i)
Each row prints the digit i at two positions.
Left diagonal
At column col === i, we print the left diagonal digit.
Right diagonal
At column col === width - i + 1, we print the mirrored digit.
Two diagonals
Everything else is spaces, so alignment depends on fixed-width spacing.
Variation — Browser (document.write) Version
In HTML, use for spaces so the diagonals don’t collapse:
<!DOCTYPE html>
<html>
<body>
<script>
var n = 5;
var width = 2 * n - 1;
for (var i = 1; i <= n; i++) {
for (var col = 1; col <= width; col++) {
if (col === i || col === width - i + 1) document.write(i);
else document.write(" ");
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Print
*instead of numbers to create an X pattern - Increase
nfor a larger mirrored diagonal grid - Use
padStartto align multi-digit row numbers - Print both diagonals for a full X by looping rows up to width
Avoid
- Using normal spaces in HTML (they collapse)
- Using proportional fonts for console output comparisons
- Forgetting to trim trailing spaces if needed
Key Takeaways
Main diagonal condition is col === i.
Mirrored diagonal condition is col === width - i + 1.
Use in HTML to preserve spacing.
This is a coordinate-rule pattern: print special values at specific columns.
❓ Frequently Asked Questions
col === row and col === width - row + 1.<pre> element or use inline-block cells with fixed width for perfect control.Explore More JavaScript Number Patterns!
Diagonal rules are powerful. Next, try mixing diagonals with borders or center columns to create complex shapes.
The two diagonal formulas col === row and col === width - row + 1 are used in many classic “X” and “cross” patterns.
12 people found this page helpful
