Repeated Number Triangle in JavaScript

What You’ll Learn
How to print a repeated number triangle in JavaScript where each row repeats the same number multiple times.
This is a great nested-loop exercise for understanding the difference between printing i and printing j.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
22
333
4444
55555Complete JavaScript Program
Outer loop chooses the row number. Inner loop repeats that row number exactly i times.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= i; j++) {
line += i;
}
console.log(line);
}🧠 How It Works
Choose row count
const rows = 5; sets the number of lines.
Outer loop (row value)
for (let i = 1; i <= rows; i++) picks which number to print on that row.
Inner loop (repeat i times)
for (let j = 1; j <= i; j++) runs i times, and line += i; repeats the row value.
Print the row
console.log(line); outputs one repeated-number row per iteration.
Repeated number triangle
Total printed digits follow 1+2+…+n = n(n+1)/2, so time complexity is O(n²).
Variation — Browser (document.write) Version
Print the same pattern directly in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
const rows = 5;
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= i; j++) {
document.write(i);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Validate rows input before generating output
- Add spaces between repeated numbers for readability
- Print repeated characters instead of numbers for variants
- Use user input to choose triangle size dynamically
- Render output in a
<pre>element via DOM APIs
Avoid
- Appending
jwhen you want repeatedi - Skipping newline output between rows
- Using non-numeric inputs without validation
- Using
document.writein production interfaces
Key Takeaways
The outer loop decides the value to be repeated on each row.
The inner loop controls how many times that value repeats.
Rows grow in size from 1 up to rows.
Changing one print statement (i vs j) creates a different pattern.
❓ Frequently Asked Questions
i = 4 and inner loop repeats output 4 times.rows = 7. The last row will print 7 repeated seven times.console.log(line) and is recommended for coding practice.n(n+1)/2.Explore More JavaScript Number Patterns!
Practice more row/column combinations to quickly master nested-loop pattern problems.
Printing i vs j inside the inner loop is one of the most common pattern-programming switches. One character change can create a totally different output.
12 people found this page helpful
