JavaScript Descending Number Pattern (Diagonal Asterisk)

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

What Is This Pattern?

Each row prints digits n..1, but when i === j the digit is replaced with * — so the star slides left as the row index grows.

Remember
Rule: for i = 1..n
      for j = n..1
        print * if i === j, else j

5432*
543*1
54*21
5*321
*4321     ← n = 5

A classic i === j diagonal trick — a natural step after the bidirectional triangle in Program 25.

How to Solve It

Outer i = 1..n; reverse j = n..1; append * when indices match, otherwise append j.

MethodIdeaBest for
i === j swapStar on the descending diagonalLearning, interviews
Custom symbolSame loops; replace * with #Variant practice
prompt inputSame loops; read size at runtimeInteractive practice

Pseudocode

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

Cheat sheet

GoalPattern
Set sizeconst n = 5;
Outer loopfor (let i = 1; i <= n; i++)
Reverse digitsfor (let j = n; j >= 1; j--)
Diagonal starif (i === j) line += "*"; else line += j;
End rowconsole.log(line);
Custom symbolline += "#"; (or any char) in the if branch

Printing Numbers vs Starting a New Line

APIEffectUse for
line += j / line += "*"Stays on the same rowEach digit or star
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 size n and the diagonal asterisk pattern updates instantly.

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

Live result n = 5 · chars = 25
5432*
543*1
54*21
5*321
*4321

JavaScript Programs

Three complete programs: fixed n = 5, custom diagonal symbol, and prompt input. Use View Output for sample results, or Try It Yourself to edit and run in the playground.

Example 1 — Fixed n = 5

Hard-coded size — reverse inner loop prints n..1 with one * where i === j.

JavaScript
const n = 5;

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

How It Works

1. Outer rows. i runs from 1 to n — also the value that becomes a star.

2. Reverse scan. j counts down from n to 1 so digits appear in descending order.

3. Swap on match. When i === j, append *; otherwise append j. Then console.log(line).

Example 2 — Custom Symbol #

Keep n = 5 but use hash instead of asterisk on the diagonal.

JavaScript
const n = 5;
const mark = "#";

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

How It Works

1. Same structure. Outer and reverse inner loops match Example 1.

2. Swap the mark. Only the if-branch string changes — mark instead of "*".

3. Same diagonal. The star still lands where i === j; only the glyph differs.

Example 3 — prompt Input

Read size at runtime; both loops use the same n.

JavaScript
const n = parseInt(prompt("Enter size:"), 10);

if (!Number.isFinite(n) || n < 1) {
  console.log("Please enter a positive integer.");
} else {
  for (let i = 1; i <= n; i++) {
    let line = "";
    for (let j = n; j >= 1; j--) {
      if (i === j) {
        line += "*";
      } else {
        line += 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 diagonal. The i === j swap scales automatically with the chosen n.

Edge Cases & Pitfalls

Check these before calling the solution done.

j++

Ascending digits

If j runs 1 to n, you get ascending digits and a different diagonal. Keep j counting down.

i == j

Wrong comparison

Use strict i === j. Comparing to a fixed column (e.g. j === 1) pins the star in one place.

log inside

Vertical output

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

n = 1

Single star

Output is just * — i and j are both 1.

n ≤ 0

Empty output

The outer loop never runs. Guard prompt input with n >= 1.

NaN input

Validate parseInt

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

Time and Space Complexity

ProgramTimeExtra space
Examples 1–3O(n²)O(n) for the current line string

Each of n rows appends exactly n characters → n² total → O(n²).

Key Takeaways

  • Rule: print n..1; swap to * when i === j.
  • Reverse j: counting down makes digits descend and the star drift left.
  • Write vs log: line += … builds; console.log(line) breaks.
  • Complexity: O(n²) for size n.

One line: scan digits downward, and replace the cell where row equals column with a star.

Frequently Asked Questions

Because i increases from 1 to n while j decreases from n to 1. The condition i === j becomes true at a different position each row.
j holds the descending column digit (n … 1). When i !== j, append that digit to fill the row.
Yes. Replace line += "*" with any character or string — see Example 2 with #.
line += j appends each digit or star on the same line. console.log(line) ends the row after the inner loop finishes.
j runs from n down to 1 so each row prints digits in descending order with the star at position i.
Replace 5 with n in both loops — see Example 3 and the live preview.
O(n²) for n rows because each row prints n characters using a nested loop.
Use parseInt(prompt(...), 10) and check Number.isFinite(n) && n >= 1 so bad input does not produce NaN.
Only one row prints — a single *.

Did you know?

This pattern prints descending numbers from n to 1 on each row. When the row index equals the current column value (i === j), it appends * instead of the number, creating a diagonal asterisk that moves left each row.

Next: Palindrome Number Triangle

Continue with the next pattern in the JavaScript number-pattern series.

Program 27 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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