Workshop › Conway's Game of Life › Step 8 of 32
The rules of Life depend on one number: how many of a cell's 8 neighbours (sides and corners) are alive. We write a function that counts them.
```js
// Live neighbours among the 8 around (r, c), skipping those off the board.
function countNeighbors(r, c) {
let count = 0
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue
const nr = r + dr
const nc = c + dc
if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS) count += grid[nr][nc]
}
}
return count
}
```r and c are parameters: the row and column we pass in, as in countNeighbors(10, 10).dr and dc over -1, 0, 1: the row above, the same and below, times the column left, same
and right. That is 9 places.continue skips (0, 0), the cell itself.if counts a neighbour only when it is on the board. Cells are 1 or 0, so we can just add them.return count hands the number back to whoever called the function.Write the function under reset, after an empty line.
Skills: Loops, Functions