Descending Numbers with Diagonal Asterisk in JavaScript

What You’ll Learn
How to print a pattern of descending numbers (5 to 1) in JavaScript and replace one position on each row with an asterisk (*) to form a diagonal.
This pattern is a good exercise for learning how an if condition works inside nested loops.
⭐ Pattern Output
For size = 5, the pattern looks like this:
5432*
543*1
54*21
5*321
*4321Complete JavaScript Program
The inner loop prints from size down to 1. When the row index equals the current value (i === j), we print * instead of the number.
const size = 5;
for (let i = 1; i <= size; i++) {
let line = "";
for (let j = size; j >= 1; j--) {
line += (i === j) ? "*" : j;
}
console.log(line);
}🧠 How It Works
Set the size
const size = 5; controls both the number of rows and the range of digits printed.
Outer loop controls rows
for (let i = 1; i <= size; i++) runs once for each output line.
Inner loop prints descending digits
for (let j = size; j >= 1; j--) traverses the digits 5, 4, 3, 2, 1.
Replace the diagonal position
When i === j, print *; otherwise print the current digit j.
Diagonal star forms naturally
The equality check picks a different position in each row, creating the diagonal.
Variation — Browser (document.write) Version
Print the pattern directly into an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var size = 5;
for (var i = 1; i <= size; i++) {
for (var j = size; j >= 1; j--) {
if (i == j)
document.write("*");
else
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change the diagonal condition to
i + j === size + 1to flip the star to the other diagonal - Replace
*with another symbol (like#or@) - Add spaces between digits for readability when size grows
- Increase
sizeto create a bigger grid
Avoid
- Swapping loop directions without updating the diagonal condition
- Forgetting the line break in browser mode
- Mixing string and numeric addition (build the row as a string)
Key Takeaways
The inner loop prints digits in descending order: size down to 1.
An if condition swaps one position per row to form a diagonal.
i === j gives a simple main-diagonal rule.
You can modify the condition to create other diagonals and shapes.
❓ Frequently Asked Questions
j = 1, so the last position becomes *, giving 5432*.if (i + j === size + 1) instead of i === j." " after each digit/star (and trim at the end) so multi-digit sizes stay readable.j downward, so the row prints as 54321. If you count upward, the row becomes 12345 and you may want a different diagonal rule.Explore More JavaScript Number Patterns!
Combine conditions and loop direction to create grids, diagonals, and framed patterns.
The condition you choose inside the inner loop (like i === j or i + j === size + 1) is often the whole key to diagonal and X-shaped patterns.
12 people found this page helpful
