JavaScript Descending Number Triangle Pattern (Right-Aligned)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A right-aligned descending number triangle prints digits i..1 on each row, padded with leading spaces so every row shares the same width and the digits sit on the right.

Remember
Rule: for i = 1..rows
        for j = rows..1
          print space if j > i else j

    1
   21
  321
 4321
54321     ← rows = 5

Natural step after left-aligned reverse triangles — once fixed-width loops and line += / console.log click, other padded patterns get easier.

How to Solve It

Grow the digit count with the outer loop; keep the inner loop fixed-width and choose space or digit.

MethodIdeaBest for
Nested loops + if/elseOuter i = 1..rows; inner j = rows..1Learning, interviews
prompt + ternarySame loops; compact (j > i) ? " " : jInteractive practice
Browser <pre>Build text, write once inside <pre>Quick HTML demos

Pseudocode

Pseudocode
for i from 1 to rows:
    line = ""
    for j from rows down to 1:
        if j > i:
            line += " "
        else:
            line += j
    print line (with newline)

Cheat sheet

GoalPattern
Set sizeconst rows = 5;
Outer loopfor (let i = 1; i <= rows; i++)
Inner loopfor (let j = rows; j >= 1; j--)
Space or digitif (j > i) line += " "; else line += j;
Ternary formline += (j > i) ? " " : j;
End rowconsole.log(line);

Printing Numbers vs Starting a New Line

APIEffectUse for
line += " " / line += jStays on the same rowEach column
console.log(line)Ends the lineAfter the inner loop

Build the row with +=, then break once with console.log. Putting console.log inside the inner loop prints one character per line.

Live Preview

Change rows and the right-aligned descending triangle updates instantly.

Whole numbers from 1 to 9. Tap a chip or type a value — the preview redraws as you go.

Live result rows = 5 · chars = 25
    1
   21
  321
 4321
54321

Worked Walkthrough — rows = 4

Trace each outer value of i, count leading spaces, and read the digits on that row.

iSpacesDigitsPrinted row
1311
222121
31321321
4043214321

Each row prints exactly rows characters — total work is O(n²) for n rows.

JavaScript Programs

Three complete programs: fixed rows = 5, prompt input with ternary, and a browser <pre> version. Use View Output for sample results, or Try It Yourself to edit and run in the playground.

Example 1 — Fixed rows = 5

Hard-coded width — if/else chooses space or digit in one fixed-width descending loop.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = rows; j >= 1; j--) {
    if (j > i) {
      line += " ";
    } else {
      line += j;
    }
  }
  console.log(line);
}
Try It Yourself

How It Works

1. Outer loop grows. i runs from 1 to rows — one right-aligned row per iteration.

2. Inner loop is fixed-width. j always runs from rows down to 1, so every row has the same length.

3. Space or digit. Append a space while j > i; otherwise append j. When i = 3 you get two spaces + 321.

Example 2 — prompt Input

Read rows at runtime. Ternary replaces if/else; the inner loop uses rows as width.

JavaScript
const rows = parseInt(prompt("Enter the number of rows:"), 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 = rows; j >= 1; j--) {
      line += (j > i) ? " " : j;
    }
    console.log(line);
  }
}
Try It Yourself

How It Works

1. Prompt and parse. Convert the answer with parseInt(..., 10).

2. Validate first. Reject NaN or non-positive values before looping.

3. Same shape. Only the source of rows changes — ternary still means “space if j > i, else digit.”

Example 3 — Browser <pre>

Same logic in the page — write the finished text inside <pre> so leading spaces stay aligned (no CSS needed).

JavaScript
<!DOCTYPE html>
<html>
<body>
<script>
const rows = 5;
let out = "";

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = rows; j >= 1; j--) {
    line += (j > i) ? " " : j;
  }
  out += line + "\n";
}

document.write("<pre>" + out + "</pre>");
</script>
</body>
</html>
Try It Yourself

How It Works

1. Same loops. Outer 1..rows, inner rows..1 — identical to Example 1.

2. Build a string. Append each finished row plus "\n" into out.

3. Preserve spaces. Wrapping in <pre> keeps leading spaces aligned without any CSS.

Edge Cases & Pitfalls

Check these before calling the solution done.

log inside

Vertical characters

If console.log is inside the inner loop, each space or digit lands on its own line. Append with +=; log only after the inner loop.

Ascending j

Wrong digit order

Counting j up from 1 prints ascending digits. Keep j = rows..1 so each row ends with i..1.

Reuse line

Growing leftovers

Reset line = "" at the start of each outer iteration, or characters from previous rows stick around.

HTML spaces

Collapsed padding

Plain document.write(line) collapses leading spaces in HTML. Use <pre> (Example 3) or console.log.

rows = 1

Single digit

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

NaN input

Validate parseInt

Letters or empty prompt yield NaN — check Number.isFinite(rows) && rows >= 1.

Time and Space Complexity

ProgramTimeExtra space
Examples 1–2O(n²)O(n) for the current line string
Browser <pre> (Example 3)O(n²)O(n²) to hold the full output string

Every row prints exactly n characters → total n × n appends → O(n²).

Key Takeaways

  • Rule: for j = rows..1, append space if j > i else j.
  • Fixed width: the inner loop always runs rows times so columns stay aligned.
  • Write vs log: line += builds; console.log(line) breaks.
  • Complexity: O(n²) for n rows.

One line: for j = rows..1, print space if j > i else j, then log the line.

Frequently Asked Questions

The inner loop always runs rows times. While j > i it appends a space; otherwise it appends j. Smaller rows get more leading spaces, so digits sit on the right.
j counts from rows down to 1. When j <= i the digit j is appended, so each row ends with i..1.
line += appends a space or digit on the same row. console.log(line) prints the finished row and starts a new line.
Program 3 is a left-aligned reverse descending triangle with no leading spaces. Program 30 pads with spaces so every row has the same width.
O(n²) for n rows. Every row runs a fixed-width inner loop of n iterations, so total work is n × n.
Yes. line += (j > i) ? " " : j is the compact form shown in Example 2.
Use parseInt(prompt(...), 10) and check Number.isFinite(rows) && rows >= 1 so bad input does not produce NaN.
One row prints with no leading spaces — just 1.

Did you know?

Each row is exactly rows characters wide. While j > i you append a space; otherwise you append j. That fixed-width inner loop is what keeps the triangle right-aligned — still O(n²).

Next: Number-Star Diamond

Continue with the number-star diamond in the JavaScript number-pattern series.

Program 31 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