Workshop › Conway's Game of Life › Step 9 of 32
One generation: every cell counts its neighbours and follows the rules. The new values go into a new grid, next,
because all cells must change at the same moment.
```js
// Every cell changes at the same moment, so the next generation is built in a new grid.
function step() {
const next = emptyGrid()
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const n = countNeighbors(r, c)
// A live cell survives with 2 or 3 neighbours; a dead cell comes alive with exactly 3.
next[r][c] = n === 3 || (n === 2 && grid[r][c] === 1) ? 1 : 0
}
}
grid = next
}
```next starts empty; the loops fill it cell by cell, reading only from grid.|| means "or", && "and". At the end grid = next makes the new generation the world.Write step under countNeighbors, after an empty line.
Skills: Game states, Loops
← Count the neighbours Draw again and again →