Generate Pascal’s Triangle in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Nested loops

What you’ll learn

  • How the triangle is built: edges are 1, inner cells are sums of the two cells above.
  • How to print a centered triangle with two nested loops and a clever coefficient update (no factorial function).
  • A second style that only adds neighbors from the previous row—same math, different code path.

Overview

Picture row zero as just 1. Each next row grows wider; the numbers are the same ones that appear in algebra when you expand (a + b)n. Programs usually print a few rows for small n so everything fits on screen.

Coefficients

Row i, position j, is “i choose j” when you count from zero.

Live preview

Pick how many rows (capped) and see the triangle in the page.

Two ways

Multiplicative step or add-the-two-above.

Prerequisites

for loops, nested loops, and integer arithmetic.

  • Basic JavaScript syntax, functions, arrays, and console.log.
  • Optional: curiosity about combinations “n choose k”—we explain just enough on this page.

The idea

Start with 1 at the top. Every new row copies 1 on both ends. Every inside slot is “what was above-left” plus “what was above-right”—that rule alone builds the whole triangle.

Computers can either mimic that addition pattern or jump between entries using a shortcut formula so you never store the whole triangle.

First five rows

Shape
        1
      1   1
    1   2   1
  1   3   3   1
1   4   6   4   1

Notice 2 = 1 + 1, 3 = 1 + 2, 6 = 3 + 3, and so on.

Live preview

Choose how many rows to print (1–14 in this demo). Uses the same multiplicative rule as Example 1.

Large row counts can lose precision in JavaScript number arithmetic.

Live result
Press “Draw triangle.”

Algorithm

Goal: for each row i from 0 to rows - 1, print i + 1 binomial values with optional leading spaces so the shape looks centered.

Outer loop: rows

Row index i runs from 0 upward.

Inner loop: entries

Generate C(i, j) for j = 0 .. i using a running value or neighbor sums.

Spacing

Print spaces before each row so the triangle tips upward in monospace output.

📜 Pseudocode

Pseudocode
for i from 0 to rows - 1:
    print leading spaces for row i
    coeff = 1
    for j from 0 to i:
        print coeff
        coeff = coeff * (i - j) / (j + 1)
    newline
1

Multiplicative update (reference style)

Matches the classic printed layout: three spaces per indent step and six-character columns. numRows = 5 reproduces the sample output below.

JavaScript
function generatePascalsTriangle(rows) {
  const lines = [];

  for (let i = 0; i < rows; i++) {
    let coefficient = 1;
    let indent = "";
    for (let s = 0; s < rows - i - 1; s++) {
      indent += "   ";
    }

    const parts = [];
    for (let j = 0; j <= i; j++) {
      parts.push(String(coefficient).padStart(6, " "));
      coefficient = Math.round((coefficient * (i - j)) / (j + 1));
    }
    lines.push(indent + parts.join(""));
  }

  return lines.join("\n");
}

console.log(generatePascalsTriangle(5));
Try it Yourself

Explanation

The inner update walks across row i without storing the whole triangle. Each new coefficient is the next binomial entry in that row.

2

Build each row from the row above

Same triangle for five rows: keep the previous row in an array, fill current row, then continue. Easy to reason about from the triangle rule.

JavaScript
function generatePascalsTriangleAdditive(rows) {
  const triangle = [];

  for (let i = 0; i < rows; 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);
  }

  const lines = [];
  for (let i = 0; i < triangle.length; i++) {
    let indent = "";
    for (let s = 0; s < rows - i - 1; s++) {
      indent += "   ";
    }
    const rowLine = triangle[i].map((n) => String(n).padStart(6, " ")).join("");
    lines.push(indent + rowLine);
  }

  return lines.join("\n");
}

console.log(generatePascalsTriangleAdditive(5));
Try it Yourself

Explanation

This is the “sum of two above” definition turned directly into arrays. It uses O(rows) auxiliary data per row construction, but the logic is easy to explain visually.

Notes

Precision limits. Entries grow quickly; for bigger rows JavaScript Number precision can lose integer exactness.

Bigger triangles. For advanced tasks, use BigInt or compute modulo a prime.

❓ FAQ

A stack of rows of numbers where every inner value equals the sum of the two numbers just above it, and the edges are all 1s.
It counts how many ways you can pick k items out of n when order does not matter. The k-th number in row n (starting from 0) is that count.
It updates the next binomial entry along the row without computing factorials. This equals C(i, j) if you start with C(i,0)=1.
For this triangle the product lands on an exact integer before division, but JavaScript numbers are floating-point. For large rows, precision can degrade.
It builds each new row by adding the two numbers above. Both examples print the same triangle for the same row count.
Printing r rows with nested loops is O(r^2) numbers. Example 1 uses O(1) extra space; Example 2 uses O(r) for row buffers.

🔄 Input / output

Change the rows argument in either example. Try small values first so the triangle stays readable.

Edge cases

rows ≤ 0

Nothing to print

Guard at the start of the generator if you accept user input.

rows = 1

Only the tip

You should see a single 1 (plus whatever spacing your loops print).

⏱️ Time and space complexity

ProgramTimeExtra space
Example 1 (multiplicative)O(rows^2) printsO(1)
Example 2 (additive rows)O(rows^2)O(rows) for buffers

Summary

  • Rule: add two neighbors above, sides stay 1.
  • Code: nested loops plus either multiplicative steps or row buffers.
  • Care: spacing and number precision on deep triangles.
Did you know?

Each entry in Pascal’s triangle is a binomial coefficient “n choose k”—the same numbers that show up in the expansion of (a + b)n.

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.

8 people found this page helpful