Number-Star Diamond Pattern in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo Operator

What You’ll Learn

The number-star diamond appends 1, 2*2, 3*3*3, … 5*5*5*5*5, then mirrors back down — a natural step after the right-aligned triangle in Program 30. This tutorial covers two outer loops, modulus alternation, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Diamond halves

Top half grows 1..n; bottom half mirrors n-1..1.

Top Loop

i = 1..n

for (let i = 1; i <= n; i++) — builds the growing half of the diamond.

Bottom Loop

i = n-1..1

for (let i = n - 1; i >= 1; i--) — mirrors the top half back down.

Modulo (j % 2)

Alternate fill

Odd j appends i; even j appends *.

Live Preview

Height 3–7

Pick a height and draw the number-star diamond in the browser.

O(n²)

Complexity

Each row appends 2*i-1 chars — total work scales as .

Introduction

A number-star diamond pattern alternates the row number and * on each line, growing to a peak then mirroring back down. With n = 5, you get 1, 2*2, … 5*5*5*5*5, then the same rows in reverse.

In JavaScript you use two outer loops (top and bottom halves) and j % 2 inside the inner loop to alternate digit and star.

Why it matters?

It combines symmetric diamond logic with the modulus operator — a step up from Program 30’s single-loop triangle.

Key Highlights

2*i-1 chars

Inner loop runs j < i*2.

j % 2

Odd appends i, even appends *.

Two halves

Top 1..n, bottom n-1..1.

Series Foundation

Follow Program 30; continue to Program 32 (triangle from 11) next.

In short: top loop i = 1..n, bottom loop i = n-1..1, inner j % 2 alternates digit and star, then console.log(line).

📝 Problem & Approach

Given n = 5, print a number-star diamond: top half i = 1..n, bottom half i = n-1..1, each row alternating digit i and * via j % 2.

JavaScript
// n = 5 (conceptual shape)
// 1
// 2*2
// 3*3*3
// 4*4*4*4
// 5*5*5*5*5
// 4*4*4*4
// 3*3*3
// 2*2
// 1

Inputs & Outputs

ItemTypeDescription
nintDiamond peak height — total lines = 2*n - 1.
iintOuter loop — current row number printed on odd positions.
jintInner loop — j % 2 == 0 appends *, else appends i.

Minimal workflow

Pseudocode
for i from 1 to n:
    line = ""
    for j from 1 to i*2-1:
        line += "*" if j % 2 == 0 else i
    console.log(line)
for i from n-1 down to 1:
    line = ""
    for j from 1 to i*2-1:
        line += "*" if j % 2 == 0 else i
    console.log(line)

Approach comparison

ApproachIdeaBest for
if/else1, 2*2, 3*3*3, …Learning and interviews
Conditional expressionline += (j % 2 === 0) ? "*" : iCompact console programs
User-input nparseInt(prompt(...), 10)Flexible diamond height

⚡ Quick Reference

GoalPattern
Top halffor (let i = 1; i <= n; i++)
Bottom halffor (let i = n - 1; i >= 1; i--)
Inner loopfor (let j = 1; j < i * 2; j++):
Alternate fillif (j % 2 === 0) { line += "*"; } else { line += i; }
Conditional formline += (j % 2 === 0) ? "*" : i
User inputparseInt(prompt(...), 10)

📋 if/else vs Conditional vs User Input

Same number-star diamond — different ways to write the modulus check and control height.

Top half
i = 1..n

Growing rows to the peak

Bottom half
i = n-1..1

Mirror back down

Modulo
"*" if j%2==0 else i

Alternate star and digit

Learning tip
2*i-1

Characters per row

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetric diamonds, the modulus operator, and two-phase loop structures.

  1. Post triangle exercise

    Natural follow-up after Program 30 — introduces modulus and a mirrored bottom half.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

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

  4. Gateway to variants

    Compare Program 30 (right-aligned triangle) and Program 32 (triangle from 11) 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 height between 3 and 7 and draw the number-star diamond in the browser.

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

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed height, user input with conditional expression form, and a smaller trace demo. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print a full diamond with n = 5 using if/else and j % 2.

Example 1 — Fixed n = 5

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

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let line = "";
  for (let j = 1; j < i * 2; j++) {
    if (j % 2 === 0) {
      line += "*";
    } else {
      line += i;
    }
  }
  console.log(line);
}

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

How It Works

When i = 1, the inner loop appends one character — 1. When i = 3, it appends 3*3*3 (five characters). The bottom half mirrors from i = 4 down to 1.

📈 User Input

Read the diamond height with prompt() instead of hard-coding 5.

Example 2 — User Input

Read n with prompt() and parseInt() to control diamond height.

JavaScript
const nInput = prompt("Enter n:");
const n = parseInt(nInput, 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 = 1; j < i * 2; j++) {
      line += (j % 2 === 0) ? "*" : i;
    }
    console.log(line);
  }

  for (let i = n - 1; i >= 1; i--) {
    let line = "";
    for (let j = 1; j < i * 2; j++) {
      line += (j % 2 === 0) ? "*" : i;
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same diamond core as Example 1; a conditional expression replaces if/else and n replaces hard-coded 5. Non-numeric input yields NaN with bare parseInt(prompt(), 10) — validate with Number.isFinite for safer labs.

⚡ Smaller Demo

Run with n = 3 to trace every row on paper before scaling up.

Example 3 — Compact n = 3

Same if/else logic with a smaller row count for quick tracing.

JavaScript
const n = 3;

for (let i = 1; i <= n; i++) {
  let line = "";
  for (let j = 1; j < i * 2; j++) {
    if (j % 2 === 0) {
      line += "*";
    } else {
      line += i;
    }
  }
  console.log(line);
}

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

How It Works

Only n changes from 5 to 3 — the if/else and two-loop structure stay identical. Trace i = 1, 2, 3 on paper to see how row length grows as 2*i-1.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed for fixed height; use prompt() when reading. Set n = 5 and loop variables i, j.

Setup
2

Top half

for (let i = 1; i <= n; i++) — growing rows from 1 to the peak.

Top
3

Inner loop (j)

for (let j = 1; j < i * 2; j++): — appends 2*i-1 characters per row.

Width
4

Modulo alternation

j % 2 == 0 appends *; odd j appends i.

Fill
5

Bottom half

for (let i = n - 1; i >= 1; i--) — mirrors the top half back down.

Mirror
=

Number-star diamond complete

2*n-1 total rows — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — top half n = 5

Trace each outer-loop value of i, inner-loop range, character count, and full row output.

iInner range (j)CharsRow output
1111
21, 2, 332*2
31..553*3*3
41..774*4*4*4
51..995*5*5*5*5

Characters per row = 2*i-1. Bottom half repeats rows 4, 3, 2, 1 in reverse.

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: flip j % 2 logic and watch stars land on wrong positions.

2. Pattern Series Base

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

Example: continue to Program 32 for a triangle starting from 11.

3. Console Formatting Drills

Practice print vs row newline without complex math.

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

4. Padding character

Add spaces between digits once the two-loop structure works.

Example: use line += i + " " between digits for wider spacing.

5. Complexity Intuition

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

Example: count printed characters for n = 5 — top half alone prints 25 chars.

6. Input Validation Labs

Pair the pattern with Number.isFinite checks and positive-row checks.

Example: reject max <= 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 C 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 n = 3 before coding — watch how row length grows as 2*i-1.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Two Outer Loops

    Top half 1..n and bottom half n-1..1 — do not repeat the peak row.

  2. 2. Validate with Number.isFinite

    Use Number.isFinite so bad input does not produce NaN when converting n.

  3. 3. Keep console.log(line) Outside the Inner Loop

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

  4. 4. Trace j % 2 on Paper

    Mark odd/even positions for each row before coding the alternation.

  5. 5. Dry-Run n = 3

    Trace i = 1..3 on paper before coding the full n = 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 number-star diamond patterns.

  1. 1. Newline Inside the Inner Loop

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

    → Use line += i or line += "*"; console.log(line) only after the inner loop.

  2. 2. Flipping Modulo Logic

    Using j % 2 != 0 for stars (instead of == 0) swaps digit and star positions.

    → Even j appends *; odd j appends i.

  3. 3. Wrong Inner Bound

    j <= i * 2 adds an extra character — row length becomes even instead of odd.

    → Keep for (let j = 1; j < i * 2; j++): for exactly 2*i-1 chars.

  4. 4. Repeating the Peak Row

    Starting the bottom loop at i = n prints the widest row twice.

    → Bottom half starts at i = n - 1, not n.

  5. 5. Bare parseInt(prompt())

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

    → Validate with Number.isFinite and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single row diamond

Output is just 1 — one row, no bottom half needed.

n = 0

Empty pattern

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

Negative

n < 0

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

n = 2

Smallest diamond

Three rows: 1, 2*2, 1.

Bad input

Non-numeric input

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

Large rows

Large row count

Total lines = 2*n - 1 — grows quadratically with peak height.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Right-aligned triangle

2. Top half only

  • Print only i = 1..n without the mirror
  • See how the growing half works alone

3. Triangle from 11

  • Continue with Program 32
  • Formula-based increasing triangle

4. Swap fill character

  • Replace * with # or .
  • Same j % 2 logic, different symbol

Notes

  • Modulo rule. Odd j appends i; even j appends *. Inner loop runs j < i*2.
  • line += builds the row; console.log(line) ends it — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 prints a single 1.
  • Bottom half starts at n - 1 — do not repeat the peak row at i = n.

Quick Takeaway: top loop i = 1..n, bottom i = n-1..1, inner j % 2 alternates digit and star, 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 number-star diamond is a compact lesson in symmetric patterns and the modulus operator: alternate i and * with j % 2, grow rows in the top half, then mirror back down. Master the fixed-n version, then try user input and a smaller trace demo.

Practice the three examples above, then continue to Program 32 for the increasing number triangle starting from 11.

Bottom half must start at n - 1 — validate n when reading from the console.

💡 Best Practices

✅ Do

  • Use top loop for (let i = 1; i <= n; i++)
  • Bottom loop for (let i = n - 1; i >= 1; i--)
  • Inner: j % 2 == 0 appends *, else appends i
  • Validate parseInt(prompt(), 10) with Number.isFinite
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call console.log(line) inside the inner loop
  • Start bottom loop at i = n (repeats peak row)
  • Use j <= i * 2 instead of j < i * 2
  • Flip the modulo condition
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this number-star diamond

Print the pattern the beginner-friendly way.

5
Core concepts
02

Two halves

Top + mirror

Code
% 03

Row width

2*i-1 chars

Code
04

Bottom start

i = n-1

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The inner loop runs for (let j = 1; j < i * 2; j++), which appends 1, 3, 5, 7, 9 characters for i = 1..5.
It checks j % 2. Even j appends '*', odd j appends the current row number i.
The first loop builds the top half (i = 1..n). The second mirrors back down (i = n-1..1) to complete the diamond.
Program 30 is a right-aligned descending triangle. Program 31 alternates digits and stars in a symmetric diamond shape.
Replace 5 with n in both outer loops — see Example 2.
O(n²) for n rows because total appended characters grow quadratically across both halves.
Use parseInt with Number.isFinite or validate the raw string before converting so bad input does not produce NaN.
Only one row prints — a single 1.
Yes — line += (j % 2 === 0) ? "*" : i compacts the if/else logic in JavaScript.

Did you Know? 🔊

This pattern prints a top half (1..n) and a bottom half (n-1..1). Each row appends 2*i-1 characters, alternating the row number and * using j % 2.

Continue to Program 32

Move on to the increasing number triangle starting from 11 in the JavaScript number-pattern series.

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