Workshop › Minesweeper › Step 5 of 26
Almost every question in Minesweeper is about a cell's neighbours: the up to eight cells around it. Two loops over the offsets -1, 0, 1 find them, skipping the cell itself and anything off the board.
```js
// The up to 8 cells around a cell, skipping the ones that would be off the board.
function neighbors(cell) {
const list = []
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue
const row = cell.row + dr
const col = cell.col + dc
if (row >= 0 && row < SIZE && col >= 0 && col < SIZE) list.push(grid[row][col])
}
}
return list
}
```dr (row offset) and dc (column offset) each take -1, 0 and 1.continue skips the rest of this turn: the offset (0, 0) is the cell itself.grid[-1] is undefined and
the next line crashes.Under the newGame function, leave an empty line and write the comment and neighbors. Press Run.
Skills: Loops, Arrays and objects
← Draw every frame Mines, but not under the first click →