Shifted Number Triangle in JavaScript

What You’ll Learn
How to print a shifted number triangle in JavaScript using nested for loops. Each row starts from the current row number and prints up to rows.
This pattern helps you understand loops where the inner loop start value changes on each row: first 1..rows, then 2..rows, then 3..rows, and so on.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
2345
345
45
5Complete JavaScript Program
The outer loop sets the row start value. The inner loop prints numbers from that start up to rows.
const rows = 5;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = i; j <= rows; j++) {
line += j;
}
console.log(line);
}🧠 How It Works
Choose the row count
const rows = 5; defines the highest number and total rows.
Outer loop (row start)
for (let i = 1; i <= rows; i++) increases the start value on each row.
Inner loop (print i..rows)
for (let j = i; j <= rows; j++) appends values from the current start i to rows.
Print each built row
console.log(line); outputs each completed row on a new line.
Shifted number triangle
The total printed values are n + (n-1) + ... + 1 = n(n+1)/2, so complexity remains 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 = i; j <= rows; j++) {
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Add spaces between digits for readability (
line += j + " ";) - Change to descending rows by reversing the outer loop direction
- Pad left spaces to align pattern to the right
- Replace numbers with letters for alphabet variants
Avoid
- Forgetting
<br>(or newline) after each row - Starting inner loop from a fixed value when pattern needs shifting start
- Using non-numeric input without conversion/validation
- Overusing
document.writein production code; prefer DOM updates
Key Takeaways
The outer loop controls the row start value from 1 to rows.
The inner loop prints from i to rows, creating a shrinking width.
Total printed values are triangular in count: n(n+1)/2.
The same nested-loop approach applies to star patterns and alphabet patterns.
❓ Frequently Asked Questions
i becomes the starting value for each row, so rows start at 1, 2, 3, and so on.for (let i = 1; i <= rows; i++) and inside it for (let j = i; j <= rows; j++). Print each j and add a newline after the inner loop.console.log(line). This is cleaner and preferred for JavaScript practice.n(n+1)/2.Explore More JavaScript Number Patterns!
Practice more nested-loop patterns and build stronger problem-solving skills with each variation.
Even though each row starts differently, the total amount of printed numbers is still a triangular number: 1+2+…+n = n(n+1)/2.
12 people found this page helpful
