0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Print Pascal Triangle

You can print Pascal's Triangle in JavaScript by using nested loops and calculating each value with triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j], then printing each row with console.log().
📋

Examples

Input5
Output1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Input1
Output1
Input0
Output
🧠

How to Think About It

To print Pascal's Triangle, think of each row as a list of numbers where the first and last numbers are always 1. Each number inside the row is the sum of the two numbers directly above it from the previous row. Start from the top row and build each row step by step using this rule.
📐

Algorithm

1
Get the number of rows to print.
2
Create an empty list to hold all rows.
3
For each row from 0 to number of rows - 1:
4
Start the row with 1.
5
For each position inside the row (except first and last):
6
Calculate value as sum of two numbers above from previous row.
7
End the row with 1 if row number is greater than 0.
8
Add the row to the list.
9
Print each row by joining its numbers with spaces.
💻

Code

javascript
function printPascalTriangle(n) {
  const triangle = [];
  for (let i = 0; i < n; i++) {
    triangle[i] = [];
    triangle[i][0] = 1;
    for (let j = 1; j < i; j++) {
      triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
    }
    if (i > 0) triangle[i][i] = 1;
  }
  for (let row of triangle) {
    console.log(row.join(' '));
  }
}

printPascalTriangle(5);
Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
🔍

Dry Run

Let's trace printing Pascal's Triangle with 3 rows through the code

1

Initialize triangle array

triangle = []

2

First row (i=0)

triangle[0] = [1]

3

Second row (i=1)

triangle[1][0] = 1; triangle[1][1] = 1; triangle[1] = [1, 1]

4

Third row (i=2)

triangle[2][0] = 1; triangle[2][1] = triangle[1][0] + triangle[1][1] = 1 + 1 = 2; triangle[2][2] = 1; triangle[2] = [1, 2, 1]

5

Print rows

Print '1', then '1 1', then '1 2 1'

RowValues
0[1]
1[1, 1]
2[1, 2, 1]
💡

Why This Works

Step 1: Start each row with 1

The first number in every row of Pascal's Triangle is always 1 because it represents the edge.

Step 2: Calculate inner values

Each inner number is the sum of the two numbers above it from the previous row using triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j].

Step 3: End each row with 1

The last number in every row (except the first) is also 1, completing the symmetrical shape.

Step 4: Print the triangle

Join each row's numbers with spaces and print them line by line to display the triangle.

🔄

Alternative Approaches

Using recursion
javascript
function pascalRow(n) {
  if (n === 0) return [1];
  const prev = pascalRow(n - 1);
  const row = [1];
  for (let i = 1; i < n; i++) {
    row[i] = prev[i - 1] + prev[i];
  }
  row.push(1);
  return row;
}

function printPascalTriangleRec(n) {
  for (let i = 0; i < n; i++) {
    console.log(pascalRow(i).join(' '));
  }
}

printPascalTriangleRec(5);
Recursion is elegant but less efficient for large rows due to repeated calculations.
Using binomial coefficients
javascript
function factorial(num) {
  let fact = 1;
  for (let i = 2; i <= num; i++) fact *= i;
  return fact;
}

function binomialCoeff(n, k) {
  return factorial(n) / (factorial(k) * factorial(n - k));
}

function printPascalTriangleBinomial(n) {
  for (let i = 0; i < n; i++) {
    let row = [];
    for (let j = 0; j <= i; j++) {
      row.push(binomialCoeff(i, j));
    }
    console.log(row.join(' '));
  }
}

printPascalTriangleBinomial(5);
Uses math formula but factorial calculations can be slow for big rows.

Complexity: O(n^2) time, O(n^2) space

Time Complexity

The program uses nested loops: the outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.

Space Complexity

It stores all rows in a 2D array, which requires O(n^2) space for n rows.

Which Approach is Fastest?

The iterative approach is faster and uses less overhead than recursion or factorial-based methods, especially for larger n.

ApproachTimeSpaceBest For
Iterative (main)O(n^2)O(n^2)Balanced speed and memory for most cases
RecursionO(n^2)O(n^2)Clear logic but slower due to repeated calls
Binomial CoefficientsO(n^3)O(n)Mathematical approach, slower for large n due to factorial
💡
Use arrays to store each row and build the next row from the previous one for easy calculation.
⚠️
Forgetting to set the first and last elements of each row to 1 causes incorrect triangle edges.