Ascending Number Triangle in JavaScript

What You’ll Learn
How to print an ascending number triangle in JavaScript using nested for loops. Each row starts at 1 and grows by one number.
This pattern is ideal for understanding how the outer loop controls row length and the inner loop prints values from 1 to the current row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
12
123
1234
12345Complete JavaScript Program
The outer loop increases row size from 1 to rows. The inner loop prints numbers from 1 to the current row limit.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= i; j++) {
line += j;
}
console.log(line);
}🧠 How It Works
Set number of rows
const rows = 5; defines the triangle height.
Outer loop (growing rows)
for (let i = 1; i <= rows; i++) increases row size one step at a time.
Inner loop (print 1..i)
for (let j = 1; j <= i; j++) appends each number up to current row limit i.
Print completed row
console.log(line); outputs one row per iteration.
Ascending number triangle
Total printed values are 1+2+…+n = n(n+1)/2, giving time complexity 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(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Validate input and handle non-positive rows safely
- Add spaces between values for clearer output
- Pad leading spaces to center the triangle shape
- Use user input to make the pattern dynamic
- Convert this to a reusable function for practice
Avoid
- Skipping row breaks after the inner loop
- Mixing up loop variables
iandj - Using wrong loop limits that overprint or underprint rows
- Relying on
document.writefor production UIs
Key Takeaways
The outer loop decides how many numbers each row contains.
The inner loop prints values from 1 to i.
Rows grow one value at a time, forming an ascending triangle.
This is a foundational loop pattern for many algorithm problems.
❓ Frequently Asked Questions
j = 1 for every row and runs until j <= i.rows. For example, set rows = 6 to print up to 123456.line for each row and print once with console.log(line).n(n+1)/2.Explore More JavaScript Number Patterns!
Keep building loop confidence by practicing more increasing and decreasing pattern programs.
The total count of numbers printed after n rows is a triangular number, which appears in many counting and combinatorics problems.
12 people found this page helpful
