JavaScript Pascal’s Triangle Program

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

What Is Pascal’s Triangle?

Pascal’s triangle is a triangular array of numbers. Edges are always 1. Every inner value is the sum of the two numbers above it. Row n (0-based) holds C(n, 0) … C(n, n).

Remember
        1
      1   1
    1   2   1
  1   3   3   1
1   4   6   4   1

Rule: value = left_parent + right_parent
(Edges have only one parent → stay 1)
RowsOutput
11
31 / 1 1 / 1 2 1
5Up through 1 4 6 4 1

How to Generate Pascal’s Triangle in JavaScript

Four clear steps — then pick an additive row build or a multiplicative coefficient fill.

  1. Decide how many rows r to print (start rows at 0 or 1 — stay consistent).
  2. Start with row [1].
  3. For each next row, edges are 1; inner cells are the sum of adjacent values from the previous row.
  4. Or fill one row at a time with C = Math.floor(C * (n - k) / (k + 1)).
MethodIdeaTimeBest for
AdditiveSum adjacent values from the previous rowO(r²)Teaching the geometric rule
MultiplicativeBuild each row with binomial updatesO(r²)No previous-row storage
Return arraysStore every row in a nested arrayO(r²)APIs / unit tests

Pseudocode

Pseudocode
function PrintPascal(rows):
    prev = [1]
    print prev

    for i from 1 to rows - 1:
        curr = [1]
        for j from 1 to length(prev) - 1:
            curr.append(prev[j - 1] + prev[j])
        curr.append(1)
        print curr
        prev = curr

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
EdgesAlways 1
Inner cellSum of the two parents above
Binomial linkRow n, spot k = C(n, k)
SymmetricC(n, k) = C(n, n - k)
Fast updateC = Math.floor(C * (n - k) / (k + 1))
Classic checkRow 4 → 1 4 6 4 1

Live Preview

Enter how many rows to print and watch the triangle grow.

Positive integers from 1 to 12. Tap a chip or type a value.

Result
rows = 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

JavaScript Programs

Start with the additive method so you can explain every cell. Then use the multiplicative update, and finish by returning nested arrays. Each example has a Try it Yourself editor.

Example 1 — Additive Rows

Keep the previous row and build the next by summing adjacent values.

JavaScript
function printPascal(rows) {
  if (rows <= 0) {
    console.log("Enter a positive number of rows.");
    return;
  }

  let prev = [1];
  console.log(prev.join(" "));

  for (let i = 1; i < rows; i++) {
    const curr = [1];
    for (let j = 1; j < prev.length; j++) {
      curr.push(prev[j - 1] + prev[j]);
    }
    curr.push(1);

    console.log(curr.join(" "));
    prev = curr;
  }
}

printPascal(5);
Try It Yourself

How It Works

  1. Reject non-positive row counts before looping.
  2. Start with prev = [1] — the top of the triangle.
  3. Each new row begins and ends with 1.
  4. Inner values are prev[j - 1] + prev[j] — the classic “two parents” rule.
  5. Replace prev with curr and repeat until rows lines are printed.

Example 2 — Multiplicative Row

Fill each row with the binomial update — no previous row required.

JavaScript
function printPascal(rows) {
  if (rows <= 0) {
    console.log("Enter a positive number of rows.");
    return;
  }

  for (let n = 0; n < rows; n++) {
    let c = 1;
    const parts = [];
    for (let k = 0; k <= n; k++) {
      parts.push(c);
      c = Math.floor((c * (n - k)) / (k + 1));
    }
    console.log(parts.join(" "));
  }
}

printPascal(5);
Try It Yourself

How It Works

  1. Outer loop chooses row index n from 0 to rows - 1.
  2. Start each row with c = 1, which is C(n, 0).
  3. Push c, then update c = Math.floor(c * (n - k) / (k + 1)) to get C(n, k + 1).
  4. Math.floor keeps coefficients whole because JavaScript division is floating-point.
  5. Same triangle as Example 1, with O(1) extra space beyond the printed line.

Example 3 — Return Arrays

Build the full triangle as a nested array — useful for tests and APIs.

JavaScript
function generate(numRows) {
  if (numRows < 1) {
    return [];
  }

  const triangle = [];
  for (let i = 0; i < numRows; i++) {
    const row = new Array(i + 1).fill(1);
    for (let j = 1; j < i; j++) {
      row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
    }
    triangle.push(row);
  }
  return triangle;
}

console.log(JSON.stringify(generate(5)));
Try It Yourself

How It Works

  1. Return an empty array when numRows < 1.
  2. Each row starts filled with 1s — edges stay correct automatically.
  3. Inner cells overwrite using the previous row’s adjacent pair.
  4. Push every completed row onto triangle.
  5. Callers can print, assert, or transform the nested arrays as needed.

Edge Cases & Pitfalls

Check these before calling the solution done.

r ≤ 0

Invalid rows

Ask for a positive row count before printing.

Indexing

0-based vs 1-based

Be clear whether row 1 is [1] or [1 1]. Stay consistent in code and tests.

Overflow

Large rows

Binomial values grow fast. Past about row 66, numbers exceed Number.MAX_SAFE_INTEGER.

Division

Multiply then floor

Use Math.floor(c * (n - k) / (k + 1)), not divide first, so intermediate results stay exact.

Time and Space Complexity

ProgramTimeExtra space
Additive rowsO(r²)O(r) for previous row
Multiplicative rowO(r²)O(1) beyond output
Return arraysO(r²)O(r²) for the full triangle

Both print about 1 + 2 + … + r = r(r+1)/2 numbers, so time is quadratic in the row count.

Key Takeaways

  • Rule: edges are 1; inner = sum of the two parents above.
  • Binomial: row n is C(n, 0) … C(n, n).
  • Update: Math.floor(c * (n - k) / (k + 1)) fills a row fast.
  • Test set: 5 rows end with 1 4 6 4 1.

One line: each inner entry is the sum of the two numbers above it — which is also C(n, k).

Frequently Asked Questions

A triangle of numbers where each edge value is 1, and every inner value is the sum of the two numbers directly above it. Row n holds the binomial coefficients C(n, 0) … C(n, n).
Build each row from the previous by adding adjacent pairs (additive method), or fill a row with the multiplicative update C = Math.floor(C * (n - k) / (k + 1)).
C(n, 0) and C(n, n) are always 1. Geometrically, nothing sits outside the triangle to add into those corners.
JavaScript division is floating-point. Each binomial update is an exact integer, so Math.floor keeps the coefficient whole.
Printing r rows needs O(r²) time. Additive uses O(r) extra space for the previous row; multiplicative can use O(1) extra beyond the output.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Next: Perfect Number

Check whether a number equals the sum of its proper divisors.

Perfect number 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.

7 people found this page helpful