JavaScript Inverted Pyramid Star Pattern

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

What Is This Pattern?

An inverted center-aligned pyramid prints the widest odd-width star row first, then narrows to a single tip star — with leading spaces so each shorter row stays centered.

Remember
Rule: for i from rows down to 1,
      print (rows - i) spaces, then (2 * i - 1) stars

*********
 *******
  *****
   ***
    *     ← 5 rows (base on top)

It is the flip of Program 5: keep the same space and star formulas, reverse only the outer loop. That mirrors how Program 2 inverts Program 1, but with odd-width centering.

How to Solve It

Two ways to emit the same shape — start with nested loops, then optionally shorten with String.repeat.

MethodIdeaBest for
Nested loopsCountdown i; spaces then odd stars via line +=Learning, interviews, exams
String.repeatBuild margin and star run in one expressionShorter demos once formulas click

Pseudocode

Pseudocode
for i from rows down to 1:
    line = ""
    for j from 1 to (rows - i):
        line += " "
    for k from 1 to (2 * i - 1):
        line += "*"
    print line

Cheat sheet

GoalPattern
Countdown rowsfor (let i = rows; i >= 1; i--)
Leading spacesfor (let j = 1; j <= rows - i; j++) line += " ";
Odd star runfor (let k = 1; k <= 2 * i - 1; k++) line += "*";
End the rowconsole.log(line);
First printed row0 spaces + 2 * rows - 1 stars
One-line shortcutconsole.log(" ".repeat(rows - i) + "*".repeat(2 * i - 1));
Upright versionfor (let i = 1; i <= rows; i++) → Program 5

Printing Stars vs Starting a New Line

APIEffectUse for
line += " " / line += "*"Stays on the same rowEach space and each *
console.log(line)Ends the current rowAfter both inner loops

Live Preview

Change the height and the inverted pyramid updates instantly — including the star total (n²).

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

Live result 5 rows · 25 stars
*********
 *******
  *****
   ***
    *

JavaScript Programs

Three complete programs: fixed rows, prompt input, and a String.repeat shortcut. Use View Output for sample results, or Try It Yourself to edit and run in the playground.

Example 1 — Fixed rows = 5

Hard-coded height — countdown outer loop with space and star inner loops.

JavaScript
let rows = 5;

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

How It Works

1. Set height. rows = 5 means five lines from base to tip.

2. Outer loop counts down. i runs from rows down to 1 — widest row first. Start a fresh line = "" each time.

3. Spaces, then stars. Append rows - i spaces, then 2 * i - 1 stars with line +=.

4. Print the row. console.log(line) after both inner loops starts the next row.

When i = 5 you get 0 spaces and 9 stars; when i = 1 you get 4 spaces and 1 star.

Example 2 — User Input Version

Read the height at runtime with prompt. Prefer validating with Number.isFinite (shown in the tip below).

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

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

How It Works

1. Prompt and parse. Ask for a row count, then convert with parseInt(..., 10).

2. Same countdown core. Only the source of rows changes — the space and star logic matches Example 1.

3. Safer input tip. Bare parseInt yields NaN on letters or Cancel. Prefer:

Safer input
let rows = parseInt(prompt("Enter the number of rows:"), 10);
if (!Number.isFinite(rows) || rows < 1) {
  console.log("Enter a positive whole number.");
} else {
  // run the pattern loops here
}

Example 3 — String.repeat for Spaces and Stars

Build each margin and odd star run in one expression — same shape, no explicit character loops.

JavaScript
let rows = 5;

for (let i = rows; i >= 1; i--) {
  console.log(" ".repeat(rows - i) + "*".repeat(2 * i - 1));
}
Try It Yourself

How It Works

1. Same countdown. Still walk i from rows down to 1.

2. Build each segment. " ".repeat(rows - i) is the margin; "*".repeat(2 * i - 1) is the star run.

3. Learn loops first. Use Examples 1–2 when you need to show nested bounds; treat this as a polish shortcut afterward.

Edge Cases & Pitfalls

Check these before calling the solution done.

i++

Upright pyramid by mistake

If you increment i from 1 to rows, you reprint Program 5. Use i-- from rows down to 1.

Tabs

Broken centering

Always append the space character " ", not tabs — tab width varies and skews the tip.

console.log inside

Column of stars

If console.log is inside either inner loop, each character lands on its own line. Use line += for spaces and stars; log only after both loops.

rows = 1

Single tip star

Output is just * — base and tip coincide. A good sanity check.

rows ≤ 0

Empty output

Outer loop never runs. Validate before looping for interactive programs.

Bad prompt

Guard against NaN

Cancel or letters yield NaN — check Number.isFinite(rows) before looping.

Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(rows) for the line string
String.repeat (Example 3)O(rows²)O(rows) per temporary row string

Total stars = 1 + 3 + … + (2n - 1) = n², plus up to Θ(n) spaces per row — still quadratic in n. Same totals as Program 5.

Key Takeaways

  • Rule: countdown i; append rows - i spaces then 2 * i - 1 stars.
  • Flip of Program 5: same formulas — only reverse the outer loop.
  • Break the row: call console.log only after both space and star loops.
  • Complexity: O(n²) time from n² stars; O(n) for the row string.

One line: for i from rows down to 1, append rows - i spaces and 2 * i - 1 stars, then console.log(line).

Frequently Asked Questions

The outer loop runs i from rows down to 1. Stars still use 2*i-1, so large i prints many stars first. As i shrinks, stars become 9,7,5,… and spaces (rows-i) grow from 0 upward. Same formulas as Program 5 — only the order of i changes.
Spaces use (rows-i). When i is rows, the margin is 0; when i is 1, the margin is rows-1. As i steps down, the margin grows while 2*i-1 shrinks, which keeps shorter rows centered under the wide top.
Program 5 uses for (let i = 1; i <= rows; i++) so stars grow. Program 6 uses for (let i = rows; i >= 1; i--) with the same inner loops, so the base prints first and the tip last.
Program 2 is an inverted left-aligned triangle (i stars, no centering). Program 6 keeps (rows-i) spaces and odd star runs so the tip stays centered.
line += stays on the same row with no newline between characters. console.log(line) ends the row after both inner loops finish.
O(n²) for n rows. Same totals as Program 5; only iteration order differs. Total stars equal n².
Yes. With the countdown outer loop: console.log(' '.repeat(rows - i) + '*'.repeat(2 * i - 1)).
Use parseInt(prompt(...), 10) and check Number.isFinite(rows) && rows >= 1 so bad input does not produce NaN rows.

Did you know?

This inverted pyramid is exactly Program 5 with the outer loop reversed — same formulas, different print order. Total stars still equal n².

Next: Inverted V Hollow

Move from a filled inverted pyramid to a hollow inverted-V outline.

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