Ascending Number Triangle in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops

What You’ll Learn

The ascending number triangle pattern grows one digit per row: nested loops, building a line string vs console.log(line), and a clear visual result. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked JavaScript examples, edge cases, and complexity.

Shape Rule

1..i digits on row i

Row 1 prints 1, row 2 prints 12, growing until row rows prints 1..rows.

Outer Loop

Rows

for (let i = 1; i <= rows; i++) walks each line from one digit up to the full width.

Inner Loop

Digits

for (let j = 1; j <= i; j++) appends digits 1 through i on that row.

print vs Newline

Same line / next line

Digits use line += j; end each row with console.log(line).

Live Preview

1–20 rows

Pick a row count and draw the ascending number triangle instantly in the browser.

O(n²)

Complexity

Total digit prints = n(n+1)/2; extra memory stays O(1).

Introduction

An ascending number triangle pattern starts with one digit on row 1 and grows by one digit each row. Each row prints consecutive digits from 1 up to i, expanding from top to bottom.

In JavaScript you solve it with two nested loops: the outer loop picks the row, the inner loop appends digits 1..i on that row, then console.log(line) moves to the next line.

Why it matters?

It is a natural follow-up after Program 4’s left-aligned descending triangle. Once nested loops and line +=/console.log(line) click, pyramids, diamonds, and hollow shapes become much easier.

Key Highlights

Row = Digit Count

On row i, print digits 1 through i.

Two Nested Loops

Outer counts up rows; inner prints digits 1..i.

Print Then Break

line += j in the inner loop; console.log(line) after.

Series Foundation

Natural step after Program 4; gateway to pyramid and hollow patterns.

In short: for each row i from 1 up to rows, append digits 1..i with line += j, then call console.log(line).

📝 Problem & Approach

Given a positive integer rows, print an ascending number triangle: each row i shows digits 1 through i, with the outer loop counting from 1 up to rows.

JavaScript
// rows = 5
// 1
// 12
// 123
// 1234
// 12345

Inputs & Outputs

ItemTypeDescription
rowsnumberNumber of triangle lines to print (typically ≥ 1).
Printed outputtextEach row prints 1..i; the first row has one digit, the last row has rows digits.

Minimal workflow

JavaScript
for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = 1; j <= i; j++) {
    line += j;
  }
  console.log(line);
}

Approach comparison

ApproachIdeaBest for
Nested loopsOuter rows + inner digitsLearning and interviews
Spaced outputline += j + " "Easier reading per row

⚡ Quick Reference

GoalPattern
Walk each rowfor (let i = 1; i <= rows; i++)
Print digits 1..ifor (let j = 1; j <= i; j++) { line += j; }
End the rowconsole.log(line);
Spaced digitsline += j + " ";
Program 1 contrastfor (let i = rows; i >= 1; i--) (descending outer)

📋 Fixed Rows vs User Input vs Spaced Output

Same ascending number triangle — different ways to control rows and formatting.

Outer loop
i = 1..rows

Counts up each row — triangle grows

Inner loop
j = 1..i

Prints ascending digits per row

Spaced digits
line += j + " "

Optional space between numbers on each row

Learning tip
parseInt(prompt())

Validate row count when reading user input

Context

When This Pattern Shows Up

Reach for this triangle when teaching or testing nested-loop basics.

  1. Post Program 4 exercise

    Natural follow-up after Program 4 — same inner loop but the outer loop counts up instead of shrinking rows.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Standard I/O practice

    Combine loops with parseInt(prompt()) for a flexible row count.

  4. Gateway to variants

    Compare Program 1 (descending outer) and Program 6 (next in series) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 9 and draw the ascending number triangle in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed rows, prompt() input, and a spaced-output variant. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print five rows of the ascending number triangle with nested loops.

Example 1 — Fixed rows = 5

Hard-coded height — ideal for first demos and screenshots.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = 1; j <= i; j++) {
    line += j;
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 1, the inner loop prints 1. When i = 5, it prints 12345 — each row adds one more digit. console.log(line) after the inner loop starts the next row.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read rows with prompt() and validate the result.

JavaScript
const rowsInput = prompt("Enter the number of rows:");
const rows = parseInt(rowsInput, 10);

if (!Number.isFinite(rows) || rows < 1) {
  console.log("Please enter a positive integer.");
} else {
  for (let i = 1; i <= rows; i++) {
    let line = "";
    for (let j = 1; j <= i; j++) {
      line += j;
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same inner-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Spaced Output

Add a space between digits for easier reading on each row.

Example 3 — Spaced Digits

Keep rows = 5 but print each digit followed by a space.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = 1; j <= i; j++) {
    line += j + " ";
  }
  console.log(line);
}
Try it Yourself

How It Works

Only the append changes — line += j + " " instead of line += j. Loop bounds stay the same as Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed. Set rows (fixed or from input).

Setup
2

Outer loop (rows)

for (let i = 1; i <= rows; i++) selects the current line, starting at one digit and growing.

Row
3

Inner loop (digits)

for (let j = 1; j <= i; j++) appends digits 1..i with line += j.

Digits
4

New line

console.log(line) ends the row so the next outer iteration starts fresh.

Break
=

Ascending triangle complete

Total digit prints: 1+2+…+n = n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i (counting up) and count how many digits the inner loop prints.

iInner j rangePrinted rowDigits this row
11..111
21..2122
31..31233
41..412344
51..5123455

Total digit prints: 1 + 2 + 3 + 4 + 5 = 15 = 5×6/2.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change j <= i and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: Program 4 shrinks each row from rows down to i.

3. Output Formatting Drills

Practice line += j vs console.log(line) without complex math.

Example: put console.log(line) inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: use line += j + " " for spaced digits on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for n = 10 → 55.

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row checks after parseInt(prompt()).

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i and j on paper for rows = 3 before coding — watch how each row grows by one digit.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Validate with Number.isFinite

    Avoid NaN when the user types letters instead of a number.

  3. 3. Keep Newline Outside

    Only call console.log(line) after the inner loop finishes the row.

  4. 4. Count Down on the Outer Loop

    1..rows with j <= i matches “row i prints digits 1..i” naturally.

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits, you almost certainly put console.log(line) inside the inner loop.

Common Pitfalls

Mistakes that commonly break ascending number triangles.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use line += j for digits; console.log(line) only after the inner loop.

  2. 2. Wrong Inner Bound

    j <= rows prints a rectangle; wrong outer bounds flatten or invert the shape.

    → For this shape, keep j <= i.

  3. 3. Forgetting the Row Break

    Omitting console.log(line) glues every digit onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Bare parseInt(prompt())

    Letters or empty input yield NaN with bare parseInt(prompt()).

    → Check Number.isFinite(rows) and re-prompt on failure.

  5. 5. Off-by-One on 0-Based Loops

    Switching to i = 0 without adjusting the inner bound prints an empty first row or wrong counts.

    → If 0-based, print digits 1..i+1 (e.g. j <= i + 1).

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit row

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric input

Bare parseInt(prompt()) returns NaN — validate with Number.isFinite first.

Fill char

Spaced digits

Try line += j + " " for spaces between numbers.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classic descending triangle

  • Outer loop counts down; inner prints 1..i
  • Compare with Program 1

2. Left-aligned descending

  • Review Program 4
  • Same outer loop, different inner bounds

3. Next in series

  • Continue with Program 6
  • Build on the same nested-loop skills

4. Spaced output

  • Use line += j + " " between digits
  • Same loops, wider visual spacing

Notes

  • Triangular count. Total digit prints for n rows is n(n+1)/2 — hence O(n²) time.
  • line += j builds the row; console.log(line) advances — call log only after the inner loop.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop picks the row, inner loop prints digits 1..i, then break the line — that is the whole pattern.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Spaced output (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The ascending number triangle pattern is a small nested-loop exercise with lasting payoff: row/column thinking, line += vs console.log(line), and O(n²) intuition. Master the fixed-rows version, then try user input and spaced output.

Practice the three examples above, then continue to Program 6 for the next pattern in the series.

Row i prints 1..i — keep line += j for digits and console.log(line) for the break, and validate row counts when reading input.

💡 Best Practices

✅ Do

  • Explain outer counts up, inner prints 1..i before coding
  • Use for (let i = 1; i <= rows; i++) in the outer loop
  • Use line += j for digits and console.log(line) after each row
  • Validate rows ≥ 1 for interactive programs
  • Use Number.isFinite when reading user input with prompt()
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call console.log(line) inside the inner digit loop
  • Use descending outer loop when you meant this ascending triangle
  • Skip the newline after each row
  • Ignore bad input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this number pattern

Print the triangle the beginner-friendly way.

5
Core concepts
02

Outer loop

Controls each row

Code
1 03

Inner loop

Appends digits with line += j

Code
04

Newline

console.log(line) ends each row

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The outer loop runs i from 1 to rows. For each row i, the inner loop runs j from 1 to i and appends j to line. Row 1 logs 1, row 2 logs 12, and so on until row rows logs 1..rows.
Because the outer loop counts up and the inner bound equals i. When i increases (1, 2, 3, ...), each row logs one more digit than the previous row.
When i = 1, the inner loop runs j from 1 to 1 — exactly one digit. Each next row adds one more value to the inner bound.
line += j builds the row string on one line. console.log(line) ends the current row. Digits use +=; the row break uses console.log after the inner loop.
Program 1 counts the outer loop down and prints 12345, 1234, ... Program 5 counts up and prints 1, 12, 123, ... — same inner loop, opposite outer direction.
Program 4 prints rows..i in descending order (54321, 5432, ...). Program 5 prints 1..i in ascending order — a growing triangle instead of a shrinking one.
Replace 5 with rows in the outer loop bound — see Example 2.
Count the outer loop down: for (let i = rows; i >= 1; i--). Keep the inner loop as for (let j = 1; j <= i; j++) — that is Program 1.
O(n²) for n rows because total logs are 1 + 2 + ... + n = n(n+1)/2.
Use parseInt with Number.isFinite. Bare parseInt(prompt()) returns NaN on bad input.
Only one row logs — a single digit 1 on one line.

Did you Know? 🔊

Row i appends digits 1 through i. The outer loop counts up from 1 to rows, so each row grows by one digit — still O(n²) total logs.

Continue to Program 6

Move on to the next pattern in the JavaScript number-pattern series.

Program 6 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful