Increasing Row-Start Number Triangle in JavaScript

What You’ll Learn
How to print a triangle where each row starts at its row number: row 1 prints 1, row 2 prints 2 3, row 3 prints 3 4 5, and so on.
This pattern is a simple way to practice nested loops plus a tiny arithmetic expression (i + j - 1).
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9Complete JavaScript Program
Row i prints i values. The value printed is i + j - 1, which starts at i when j = 1.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= i; j++) {
line += (i + j - 1) + (j === i ? "" : " ");
}
console.log(line);
}🧠 How It Works
Set the number of rows
const rows = 5; sets the height of the triangle.
Outer loop selects the row
i goes from 1..rows. Row i will print i numbers.
Inner loop prints columns 1..i
j runs from 1..i so the row length grows by one each line.
Compute the printed value
The expression i + j - 1 starts at i and increases by 1 for each column.
Row starts at i
Row 4 starts at 4 and prints 4 values: 4, 5, 6, 7.
Variation — Browser (document.write) Version
Print the triangle in 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; j++)
document.write(i + j - 1 + " ");
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change the starting value by adding an offset:
(offset + i + j - 1) - Use
padStartto align columns for larger values - Print the triangle in reverse by looping
ifromrowsdown to 1 - Replace the formula with
i * jfor multiplication patterns
Avoid
- Leaving trailing spaces in console output when comparing exact output
- Printing without separators (numbers may run together)
- Hard-coding row counts if you want a reusable pattern function
Key Takeaways
Row i prints exactly i values (triangle growth).
The formula i + j - 1 makes each row start at i.
Changing the expression changes the entire pattern.
Nested loops are the foundation for most pattern-printing programs.
❓ Frequently Asked Questions
i + j - 1 for j = 1..5, resulting in 5, 6, 7, 8, 9.j in the expression (for example, just print i).(j - 1) as the printed value for each row.Explore More JavaScript Number Patterns!
Small formulas like i + j - 1 can generate surprisingly rich patterns.
Patterns that use i + j are closely related to “diagonals” in a grid. Each diagonal shares the same sum, which is why these patterns look like shifted sequences.
12 people found this page helpful
