Number and Asterisk Diamond Pattern in JavaScript

What You’ll Learn
How to print a pattern that grows from 1 to 5 and then shrinks back down, with * between repeated numbers: 3*3*3, 4*4*4*4, etc.
You’ll learn how to use two outer loops (up and down) to create a diamond-like structure.
⭐ Pattern Output
For this example, the pattern looks like this:
1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4
3*3*3
2*2
1Complete JavaScript Program
Each row prints 2*i - 1 characters. Odd positions print the number i; even positions print *. We print rows 1..5, then 4..1 to mirror the shape.
const max = 5;
function printRow(i) {
let line = "";
for (let j = 1; j < i * 2; j++) {
line += (j % 2 === 0) ? "*" : String(i);
}
console.log(line);
}
for (let i = 1; i <= max; i++) {
printRow(i);
}
for (let i = max - 1; i >= 1; i--) {
printRow(i);
}🧠 How It Works
Set the maximum row value
const max = 5; controls the widest row: 5*5*5*5*5.
Row length is 2*i - 1
The loop for (j = 1; j < i*2; j++) runs exactly 2*i - 1 times.
Alternate number and *
Odd positions print i, even positions print * using j % 2.
Mirror the bottom half
After printing rows 1..5, printing 4..1 creates the symmetric lower half.
Diamond-style pattern
The pattern grows and then shrinks, keeping the same row-generation rule.
Variation — Browser (document.write) Version
Print the pattern directly into an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j < i * 2; j++) {
if (j % 2 == 0)
document.write("*");
else
document.write(i);
}
document.write("<br>");
}
for (i = 4; i >= 1; i--) {
for (j = 1; j < i * 2; j++) {
if (j % 2 == 0)
document.write("*");
else
document.write(i);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
maxto make the diamond taller - Replace
*with another separator like-or@ - Print spaces around the separator for readability (e.g.,
" * ") - Center-align the diamond by printing leading spaces before each row
Avoid
- Printing the bottom half starting from
maxagain (duplicates the middle row) - Using
j <= i*2(adds an extra character) - Forgetting to add a line break after each row
Key Takeaways
Each row prints 2*i - 1 characters.
Odd positions print the number; even positions print *.
Two outer loops (up and down) create the diamond shape.
Mirroring avoids re-writing a different row-generation rule for the bottom.
❓ Frequently Asked Questions
2*4 - 1 = 7 positions, and the code alternates: 4, *, 4, *, 4, *, 4.max - 1 to 1.line and print it once using console.log.Explore More JavaScript Number Patterns!
Try combining repetition, separators, and mirroring to create more complex patterns.
Many diamond patterns can be generated by printing an increasing sequence and then printing the same sequence in reverse—often with max - 1 to avoid duplicating the middle row.
12 people found this page helpful
