Right-Aligned Number Triangle in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Spacing + Loops

What You’ll Learn

The right-aligned number triangle prints 1, then 1 2, then 1 2 3, … — a natural follow-up after Program 42’s hollow square border. This tutorial covers leading-space indentation, ascending sequences, nested loops, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Right-aligned triangle

Row i prints numbers 1 to i, with leading spaces before the digits.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) — ascending outer loop, one row per iteration.

Space Loop

rows..i+1

" ".repeat(rows - i) — adds leading spaces for right alignment.

Number Loop

line +=

for (let k = 1; k <= i; k++) then line += k + " ".

Live Preview

3–9 rows

Pick a row count and draw the right-aligned number triangle in the browser.

O(n²)

Complexity

Total prints = n(n+1)/2 — work scales as .

Introduction

A right-aligned number triangle prints numbers from 1 to i on each row: 1, then 1 2, then 1 2 3, and so on. With rows = 5, shorter rows shift right thanks to a leading-space loop.

In JavaScript you build each row with line += " ".repeat(rows - i) for leading spaces, then line += k + " " for k = 1..i, then console.log(line).

Why it matters?

It combines a space loop with an ascending number loop — a key step after Program 42’s hollow grid pattern.

Key Highlights

1..i

Ascending sequence.

Space loop

rows - i spaces.

line +=

Readable column spacing.

Series Foundation

Follow Program 42; continue to Program 44 next.

In short: outer i = 1..rows, leading spaces " ".repeat(rows - i), numbers k = 1..i with line += k + " ", then console.log(line).

📝 Problem & Approach

Given rows = 5, print a right-aligned ascending triangle: leading spaces while j > i, then numbers from 1 to i.

JavaScript
// rows = 5
//    1
//   1 2
//  1 2 3
// 1 2 3 4
//1 2 3 4 5

Inputs & Outputs

ItemTypeDescription
rowsnumberTriangle height — also controls leading-space count.
inumberOuter loop — current row number (1 to rows).
knumberNumber loop — prints digits 1..i.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from rows down to i+1: print one space
    for k from 1 to i: print k with trailing space
    print newline

Approach comparison

ApproachIdeaBest for
Fixed rows1, 1 2, …Learning and interviews
User-input rowsparseInt(prompt(), 10)Configurable triangle size
Left-aligned variantRemove space loopContrast with right alignment

⚡ Quick Reference

GoalPattern
Outer loopfor (let i = 1; i <= rows; i++)
Leading spacesline += " ".repeat(rows - i)
Number loopfor (let k = 1; k <= i; k++)
Append numberline += k + " "
End the rowconsole.log(line)
Program 42 contrastHollow square grid — not an ascending triangle

📋 Fixed vs User Input vs Left-Aligned

Same ascending triangle — different ways to control rows and alignment.

Outer loop
i = 1..rows

One row per iteration

Spaces
rows - i

Leading-space indent

Numbers
k = 1..i

Ascending sequence

Left-aligned
skip space loop

Flush-left triangle

Context

When This Pattern Shows Up

Reach for this pattern when teaching dual inner loops, ascending sequences, and right-aligned console output.

  1. After Program 42

    Natural follow-up — moves from a 2D grid with border conditions to a triangle with leading spaces and ascending digits.

  2. Dual inner-loop drills

    Practice separating space printing from number printing before tackling more complex shapes.

  3. Console I/O practice

    Combine loops with prompt() for flexible row counts.

  4. Gateway to variants

    Compare Program 42 (hollow square) and Program 44 (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 dual inner loops, formatted output, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 9 and draw the right-aligned number triangle in the browser.

Try 3, 5, or 7. Rows between 3 and 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

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

📚 Getting Started

Print five rows of the right-aligned number triangle with space and number loops.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

JavaScript
const rows = 5;

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

How It Works

When i = 1, the space loop prints four spaces, then 1. When i = 5, no leading spaces — output 1 2 3 4 5.

📈 User Input

Read the row count with prompt() instead of hard-coding 5.

Example 2 — User input rows

Read rows with prompt() and validate rows > 0 (check with Number.isFinite in real apps).

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

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

How It Works

Same space-and-number loop core as Example 1; only rows comes from user input instead of being hard-coded as 5.

⚡ Left-Aligned Contrast

Remove the space loop to see how right alignment changes the shape.

Example 3 — Left-Aligned Triangle

Same ascending sequence without leading spaces — numbers start flush left.

JavaScript
const rows = 5;

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

How It Works

Only the space loop is removed — the number loop stays the same. Compare this flush-left output with Example 1 to see what the space loop contributes.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed. Set rows = 5 and loop variables i, k.

Setup
2

Outer loop walks rows

for (let i = 1; i <= rows; i++) — ascending outer loop; one row per iteration.

Row
3

Space loop

line += " ".repeat(rows - i) — adds leading spaces for right alignment.

Align
4

Number loop

for (let k = 1; k <= i; k++) then line += k + " " — ascending sequence.

Print
5

New line

console.log(line) ends the row after both inner steps finish.

Break
=

Right-aligned triangle complete

Total numbers = n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5, row i = 3

Trace row 3 — space count, numbers printed, and full row output.

StepDetailOutput so far
Space loop" ".repeat(2) — two spaces
k = 1line += "1 "1
k = 2line += "2 "1 2
k = 3line += "3 "1 2 3
NewlineEnd row 31 2 3

Space count per row = rows - i. Numbers per row = i. Total prints = n(n+1)/2 for n rows.

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: remove the space loop and watch the triangle snap left.

2. Pattern Series Base

Foundation for right-aligned variants with separate space and number loops.

Example: compare with Program 42 (hollow square) and Program 44 next.

3. Console Formatting Drills

Practice line += spacing and row newlines without complex math.

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

4. Padding spaces

Add leading spaces once the three-loop structure works.

Example: loop k from i down to 1 for a descending row variant.

5. Complexity Intuition

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

Example: count printed numbers for rows = 5 — total is 1+2+3+4+5 = 15.

6. Input Validation Labs

Pair the pattern with Number.isFinite and prompt() validation.

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, the space loop, and the number loop on paper for rows = 3 before coding — watch how the space count shrinks each row.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Two Inner Loops

    Leading spaces (" ".repeat(rows - i)) and number loop (k = 1..i) must run in order before console.log(line).

  2. 2. Validate with Number.isFinite

    Use Number.isFinite(rows) so bad prompt() input does not crash when converting rows.

  3. 3. Keep console.log Outside the Inner Loop

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

  4. 4. Trace 1..i on Paper

    Write the ascending sequence 1..i on paper before coding the number loop.

  5. 5. Dry-Run rows = 3

    Trace i = 1..3 on paper before coding the full rows = 5 demo.

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

Common Pitfalls

Mistakes that commonly break right-aligned 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 += k + " "; console.log(line) only after both inner steps.

  2. 2. Skipping the Space Loop

    Without " ".repeat(rows - i), every row starts at the left margin.

    → Run the space loop before the number loop on every row.

  3. 3. Mixing Logic in One Loop

    Combining spaces and numbers in a single inner loop is harder to read and debug.

    → Keep separate space and number loops — see Examples 1 and 3.

  4. 4. Using Tabs for Spacing

    Tab characters produce inconsistent alignment across consoles.

    → Use line += " ".repeat(rows - i) for leading spaces.

  5. 5. Bare parseInt(prompt())

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

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

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 on one line — no leading spaces when rows = 1.

rows = 0

Empty pattern

Outer loop never runs when rows < 1 — print nothing or show a message.

Negative

rows < 1

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

rows = 2

Smallest triangle

Two rows: 1 and 1 2.

Bad input

Non-numeric input

Bare parseInt(prompt()) yields NaN on bad input — use Number.isFinite first.

Large rows

Large row count

Total numbers = rows(rows+1)/2 — grows quadratically with rows.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Hollow square

  • Review Program 42
  • Compare grid border logic with triangle indentation

2. Next in series

  • Continue with Program 44
  • Next pattern in the number-pattern series

3. Sequence trace

  • Prove on paper: row i prints 1 to i
  • Space count = rows - i

4. Safe input loop

  • Check Number.isFinite(rows) after parseInt(prompt())
  • Then draw the triangle

Notes

  • Loop rule. Outer i = 1..rows. Leading spaces " ".repeat(rows - i). Number loop k = 1..i appends with line += k + " ".
  • Build each row with line +=, then console.log(line) once per row.
  • Validate rows ≥ 1 for interactive programs; rows = 1 prints a single 1.
  • Space count = rows - i — compare with Example 3 where removing the space loop gives a left-aligned triangle.

Quick Takeaway: outer i = 1..rows, leading spaces " ".repeat(rows - i), numbers k = 1..i with line += k + " ", then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The right-aligned number triangle is a compact lesson in dual inner loops and formatted output: append spaces with " ".repeat(rows - i), append 1..i with line += k + " ", and end each row with console.log(line). Master the fixed-rows version, then try user input and the left-aligned contrast.

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

Leading spaces create right alignment — keep space and number loops separate and validate rows when reading input.

💡 Best Practices

✅ Do

  • Use for (let i = 1; i <= rows; i++) in the outer loop
  • Leading spaces: line += " ".repeat(rows - i)
  • Number loop: for (let k = 1; k <= i; k++) line += k + " "
  • Validate rows ≥ 1 for interactive programs
  • Check Number.isFinite(rows) after parseInt(prompt())

❌ Don’t

  • Call console.log(line) inside the number loop
  • Skip the leading-space loop for right alignment
  • Mix alignment and number printing in one loop
  • Use tabs for spacing (results vary across consoles)
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this right-aligned number triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Rows i = 1..rows

Code
03

Space loop

rows - i spaces

Align
04

Number loop

k = 1..i

Code
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A right-aligned ascending triangle: row 1 prints 1, row 2 prints 1 2, row 3 prints 1 2 3, and so on until 1 2 3 4 5.
Before appending numbers, the program adds leading spaces with " ".repeat(rows - i). Smaller rows get more spaces, pushing digits to the right edge.
Yes. Change line += k + " " to line += String(k) if you want the numbers to touch.
Skip the leading-space step. Just append numbers from 1 to i on each row — see Example 3.
Program 42 prints a hollow square grid with border conditions. Program 43 prints an ascending number triangle with indentation spaces.
Use a rows variable and loop i from 1 to rows — see Example 2.
O(n²) for n rows because total appends are 1 + 2 + ... + n = n(n+1)/2.
Use parseInt with Number.isFinite and validate rows > 0 before printing.
Only one row prints — a single 1 with no leading spaces.

Did you Know? 🔊

Each row appends numbers 1 to i. Leading spaces use " ".repeat(rows - i) before the number loop; line += k + " " keeps columns readable in the output.

Continue to Program 44

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

Program 44 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.

12 people found this page helpful