Repeating Number Pattern (Decreasing Length) in JavaScript

What You’ll Learn
How to print a repeating number pattern where each row repeats the same digit, and the row length decreases from 5 down to 1.
You’ll also learn a simple mirroring trick so the last rows print 22 and 1 instead of 4444 and 55555.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
11111
2222
333
22
1Complete JavaScript Program
The inner loop prints rows - i + 1 characters on each row. The value is i for the first three rows, then mirrored using rows + 1 - i.
const rows = 5;
for (let i = 1; i <= rows; i++) {
const count = rows - i + 1;
const value = i < 4 ? i : (rows + 1 - i);
console.log(String(value).repeat(count));
}🧠 How It Works
Choose the row count
const rows = 5; sets the height and the maximum row length.
Outer loop controls rows
for (let i = 1; i <= rows; i++) runs once per line of output.
Compute how many times to print
count = rows - i + 1 decreases by 1 each row, producing lengths 5, 4, 3, 2, 1.
Pick the digit value (mirror)
For i < 4, use i. Otherwise use rows + 1 - i to mirror back down.
Row is generated by repetition
String(value).repeat(count) builds each output line in one step.
Variation — Browser (document.write) Version
Print the same pattern directly into an HTML page:
<!DOCTYPE html>
<html>
<body>
<script>
var rows = 5;
for (var i = 1; i <= rows; i++) {
for (var j = i; j <= rows; j++) {
if (i < 4)
document.write(i);
else
document.write(rows + 1 - i);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
rowsto generate a bigger or smaller pattern - Replace the digit with another value (like
rows - i + 1) to explore different sequences - Add a space between digits (useful when values become 2-digit numbers)
- Build the line using an inner loop instead of
repeatfor more control
Avoid
- Hard-coding
i < 4if you later change the number of rows; adjust the mirror point accordingly - Forgetting the line break in browser mode
- Mixing row and column counters (keep
ifor rows,jfor columns)
Key Takeaways
Row length is controlled by decreasing columns: rows - i + 1.
The printed digit can be mirrored using rows + 1 - i.
repeat is a simple way to generate repeated characters quickly.
The same idea can be used to print letter or symbol patterns.
❓ Frequently Asked Questions
rows + 1 - i) so the digits step back down as the row length shrinks.repeat, build the line with a loop and append " " after each digit.Math.ceil(rows / 2) + 1 depending on the pattern you want, then mirror after that threshold.repeat for simplicity.Explore More JavaScript Number Patterns!
Keep practicing loops by mixing repetition, mirroring, and spacing techniques.
Many pattern problems can be reduced to two choices: (1) how many characters to print, and (2) what value to print. Once you compute both, printing becomes straightforward.
12 people found this page helpful
