Emmanuel Akinfulubi

JavaScriptBasic

Generate Pascal's triangle in JavaScript

Intermediate · 4 min read

Pascal's triangle is a stack of numbers where each number is the sum of the two just above it. It looks like a puzzle, but it turns up in real maths: probability, counting combinations, and expanding brackets like (a + b)⁴. It's also a classic exercise in building one row from the row before.

In this tutorial you will write pascal(rows), which builds the first rows of the triangle as arrays, and render(rows), which prints them centered. You need to know arrays and for loops. The rule is explained below with a picture.

How the triangle grows

Output

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
  • The first row is just 1.
  • Every row starts and ends with 1.
  • Every number inside is the two numbers above it added together. The 6 in the last row is 3 + 3, from the row above.
  • Each row is one number longer than the last.

Row 0 has one number, row 1 has two, and row r has r + 1.

A missing neighbor counts as 0

Here's a neat way to handle the edges. Imagine the row above has invisible zeros on both sides: 0 1 3 3 1 0. Then every number in the new row, edges included, is the sum of two neighbors above: 0 + 1 = 1, 1 + 3 = 4, 3 + 3 = 6, and so on.

In JavaScript, reading past the end of an array gives undefined. undefined || 0 gives 0, so (above[c] || 0) reads a missing neighbor as zero:

JavaScript

const above = [1, 3, 3, 1];
console.log(above[4]);       // undefined
console.log(above[4] || 0);  // 0
console.log((above[-1] || 0) + (above[0] || 0)); // 1

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

135 Pascal’s triangle

fair

Build the first n rows of Pascal's triangle, where every number is the sum of the two above it and the edges are 1. Then render it centred. Asking for zero rows should give nothing, not a row.

Stuck? Three hints, smallest first
  1. 1. Each row starts at 1 and is one longer than the row above.
  2. 2. The inner value at column c is previous[c - 1] + previous[c]; treat a missing neighbour as 0.
  3. 3. To centre a line, pad it to half the difference between its length and the widest line.

Step 1: build one row from the row above

Step 1

function nextRow(above) {
  const row = [1];
  for (let c = 1; c <= above.length; c++) row.push((above[c - 1] || 0) + (above[c] || 0));
  return row;
}
console.log(nextRow([1]));          // [ 1, 1 ]
console.log(nextRow([1, 3, 3, 1])); // [ 1, 4, 6, 4, 1 ]

The row starts with [1]. Then, for each column c, we add the number above-left (c - 1) and the number above (c). The last column has nothing above it, so it's 1 + 0 = 1, and the right edge comes out without a special case.

Step 2: build many rows

Step 2

function pascal(rows) {
  const out = [];
  for (let r = 0; r < rows; r++) {
    const above = out[r - 1] || [];
    const row = [1];
    for (let c = 1; c <= r; c++) row.push((above[c - 1] || 0) + (above[c] || 0));
    out.push(row);
  }
  return out;
}
console.log(pascal(4)); // [ [ 1 ], [ 1, 1 ], [ 1, 2, 1 ], [ 1, 3, 3, 1 ] ]
console.log(pascal(0)); // []

Row r needs the row before it, out[r - 1]. For the very first row, r is 0 and out[-1] is undefined. Reading undefined[0] would throw an error, so || [] swaps in an empty array.

The inner loop runs c from 1 to r, so row r ends up with r + 1 numbers.

Asking for zero rows means the outer loop never runs, and you get an empty triangle rather than a row with a 1 in it.

Step 3: something hiding in the rows

Add up each row:

Step 3

function pascal(rows) {
  const out = [];
  for (let r = 0; r < rows; r++) {
    const above = out[r - 1] || [];
    const row = [1];
    for (let c = 1; c <= r; c++) row.push((above[c - 1] || 0) + (above[c] || 0));
    out.push(row);
  }
  return out;
}
console.log(pascal(8).map((r) => r.reduce((a, b) => a + b, 0)).join(' ')); // 1 2 4 8 16 32 64 128
console.log(pascal(7)[6]); // [ 1, 6, 15, 20, 15, 6, 1 ]

The sums double every row: they're powers of two. The numbers in row r count how many ways you can choose some items from r items. Row 6, position 2, is 15: there are 15 ways to pick 2 people from a group of 6. So this loop is a way to count combinations using only addition.

Step 4: print it centered

To center a line, put half of the missing space on the left. The widest line is the last one. padStart with a length of (width + length) / 2 adds exactly half the difference in front:

Step 4

function pascal(rows) {
  const out = [];
  for (let r = 0; r < rows; r++) {
    const above = out[r - 1] || [];
    const row = [1];
    for (let c = 1; c <= r; c++) row.push((above[c - 1] || 0) + (above[c] || 0));
    out.push(row);
  }
  return out;
}
function render(rows) {
  const lines = pascal(rows).map((row) => row.join(' '));
  const width = lines.length ? lines[lines.length - 1].length : 0;
  return lines.map((l) => l.padStart(Math.floor((width + l.length) / 2)).padEnd(width));
}
for (const line of render(5)) console.log('[' + line + ']');
console.log(render(0)); // []

The brackets in the output show the padding:

Output

[    1    ]
[   1 1   ]
[  1 2 1  ]
[ 1 3 3 1 ]
[1 4 6 4 1]

Take the first line: the width is 9 and '1' is 1 long, so it's padded to (9 + 1) / 2 = 5 characters, four spaces then the 1. Then padEnd(width) fills the right side, so every line is exactly 9 wide. Without padEnd the lines would look centered but have different lengths, which breaks anything lined up next to them.

Math.floor keeps the length a whole number when the difference is odd.

The full solution

The answer panel has pascal and render, prints a five-row triangle and the row sums for eight rows. The checks cover the first six rows, the row lengths, the edges, the symmetry, combinations, and the empty triangle. Press Run to see the output.

The answer

function pascal(rows) {
  const out = [];
  for (let r = 0; r < rows; r++) {
    const above = out[r - 1] || [];
    const row = [1];
    for (let c = 1; c <= r; c++) row.push((above[c - 1] || 0) + (above[c] || 0));
    out.push(row);
  }
  return out;
}

function render(rows) {
  const lines = pascal(rows).map((row) => row.join(' '));
  const width = lines.length ? lines[lines.length - 1].length : 0;
  // padStart to (width + length) / 2 puts half the shortfall on the left.
  return lines.map((l) => l.padStart(Math.floor((width + l.length) / 2)).padEnd(width));
}

const six = pascal(6);
for (const line of render(5)) console.log(line);
console.log('row sums:', pascal(8).map((r) => r.reduce((a, b) => a + b, 0)).join(' '));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the first six rows', six, [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]);
test('row r has r + 1 entries', six.map((r) => r.length), [1, 2, 3, 4, 5, 6]);
test('the ends are always 1', six.every((r) => r[0] === 1 && r[r.length - 1] === 1), true);
test('each row reads the same backwards', six[5], [...six[5]].reverse());
test('and each row adds up to a power of two', pascal(8).map((r) => r.reduce((a, b) => a + b, 0)), [1, 2, 4, 8, 16, 32, 64, 128]);
test('the entries are the binomial coefficients, so row 6 column 2 is 6 choose 2', [pascal(7)[6], pascal(7)[6][2]], [[1, 6, 15, 20, 15, 6, 1], 15]);
test('zero rows is an empty triangle, not a row containing one', [pascal(0), pascal(1)], [[], [[1]]]);
test('the render is centred and every line is the width of the last', render(5), ['    1    ', '   1 1   ', '  1 2 1  ', ' 1 3 3 1 ', '1 4 6 4 1']);
test('and an empty triangle renders as nothing at all', render(0), []);

The inner loop is the exercise: above[c - 1] + above[c], with a missing neighbour read as 0 so the edges fall out of the same expression instead of needing their own if. Note out[r - 1] || [] for the first row — out[-1] is undefined, and indexing into it would throw, which is the one place this can go wrong.

Row sums being powers of two is not decoration. Row r of the triangle is the binomial coefficients of r choose k, and they sum to 2r because that counts every subset of r things. So this loop is also a way to compute combinations without factorials, which matters because 21! already exceeds what a JavaScript number can hold exactly while every entry in these rows stays a small integer.

The centring is arithmetic worth reading twice. padStart((width + length) / 2) asks for a string whose length is the midpoint, which adds exactly half the shortfall on the left; padEnd(width) then fills the right so every line is the same length. Without the padEnd the lines look centred and are not the same width, which shows up the moment anything is aligned against them.

Common mistakes

  • Reading out[r - 1] without a fallback. For the first row it's undefined, and indexing into it throws.
  • Writing separate code for the edges. Treat a missing neighbor as 0 and the edges work out by themselves.
  • Centering with padStart alone. The lines end up with different lengths. Add padEnd(width).

Try it yourself

  1. Write choose(n, k) that returns pascal(n + 1)[n][k], and check choose(6, 2) is 15.
  2. Print only the odd numbers as * and the even ones as a space, for 16 rows. What shape appears?
  3. Build each row from the previous one without keeping the whole triangle, to print row 30 using very little memory.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.