Emmanuel Akinfulubi

JavaScriptBasic

Check the winner of tic-tac-toe in JavaScript

Advanced · 4 min read

Tic-tac-toe is often the first game people build when they learn to code. Drawing the board is the easy part. The interesting part is the referee: after every move, the game has to decide whether someone has won, whether it is a draw, or whether play goes on.

In this tutorial you will write winner, a function that looks at a board and gives one of three answers. Along the way you will meet a bug that makes an empty board look like a win. You need to know arrays, loops and if. Everything else is explained as we go.

The board as an array

A tic-tac-toe board has nine cells. The simplest way to store it is an array of nine strings: 'X', 'O', or '' for an empty cell. The positions are numbered like this:

Output

0 | 1 | 2
3 | 4 | 5
6 | 7 | 8

So board[4] is the center, and board[0], board[4] and board[8] form a diagonal.

Eight ways to win

There are only eight winning lines: three rows, three columns and two diagonals. Instead of writing eight separate if statements, we can list them as data, each line being three positions:

JavaScript

const LINES = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],   // rows
  [0, 3, 6], [1, 4, 7], [2, 5, 8],   // columns
  [0, 4, 8], [2, 4, 6],              // diagonals
];
console.log(LINES.length); // 8

Now the code can loop over the lines, and a bigger board would only need a longer list.

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

123 Who won the tic-tac-toe game

hard

Given nine cells holding 'X', 'O' or '', report the winner, or a draw, or that the game is still going. Make sure a board of empty cells is not declared a win by three matching blanks.

Stuck? Three hints, smallest first
  1. 1. List the eight winning lines once, as index triples, and loop over them.
  2. 2. A line only counts if the first cell is actually occupied.
  3. 3. Full board and no line is a draw; an unfinished board is neither.

Step 1: check each line

for (const [a, b, c] of LINES) takes each line and unpacks its three numbers into a, b and c. This is called destructuring. A line is won when all three cells hold the same mark.

Step 1

const LINES = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],
  [0, 3, 6], [1, 4, 7], [2, 5, 8],
  [0, 4, 8], [2, 4, 6],
];
function naive(board) {
  for (const [a, b, c] of LINES) {
    if (board[a] === board[b] && board[b] === board[c]) return board[a];
  }
  return null;
}
const row = ['X', 'X', 'X', 'O', 'O', '', '', '', ''];
console.log(naive(row)); // X

This finds the top row of X. It looks finished, but try an empty board:

JavaScript

const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
function naive(board) {
  for (const [a, b, c] of LINES) {
    if (board[a] === board[b] && board[b] === board[c]) return board[a];
  }
  return null;
}
const empty = Array(9).fill('');
console.log(JSON.stringify(naive(empty))); // "": three blanks count as a line

Three empty cells are equal to each other, so the very first row "wins", and the winner is the empty string. Because '' is falsy, if (naive(board)) happens to behave, so this bug can hide for a long time. It shows up the day someone prints the winner or compares it with null.

Step 2: only count occupied lines

The fix is to ask whether the first cell has a mark before comparing the line.

Step 2

const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
function winner(board) {
  for (const [a, b, c] of LINES) {
    const mark = board[a];
    if (mark && mark === board[b] && mark === board[c]) return mark;
  }
  return null;
}
console.log(winner(Array(9).fill(''))); // null
console.log(winner(['X', 'O', '', 'X', 'O', '', '', 'O', ''])); // O: the middle column

mark && stops the check straight away when the cell is '', because '' is falsy. Now an empty board is undecided.

Step 3: tell a draw from a game in progress

When no line is won, there are still two possibilities. If every cell is filled, it is a draw. If any cell is empty, the game is still going. every answers "is this true for every item?":

Step 3

const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
function winner(board) {
  for (const [a, b, c] of LINES) {
    const mark = board[a];
    if (mark && mark === board[b] && mark === board[c]) return mark;
  }
  return board.every((cell) => cell) ? 'draw' : null;
}
console.log(winner(['X', 'O', 'X', 'X', 'O', 'O', 'O', 'X', 'X'])); // draw
console.log(winner(['X', 'O', '', '', '', '', '', '', '']));         // null

Three different outcomes get three different values: a mark, 'draw', or null for "still playing". If "no winner yet" and "drawn" shared one value, the game could announce a draw after two moves.

Step 4: win before draw

The order of the checks matters. A full board can still contain a winning line:

Step 4

const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
function winner(board) {
  for (const [a, b, c] of LINES) {
    const mark = board[a];
    if (mark && mark === board[b] && mark === board[c]) return mark;
  }
  return board.every((cell) => cell) ? 'draw' : null;
}
const wonAndFull = ['X', 'X', 'X', 'O', 'O', 'X', 'O', 'X', 'O'];
console.log(winner(wonAndFull)); // X

If the function checked "is the board full?" first, it would call this game a draw. Looking for lines first, and only then counting empty cells, gives X the win.

The full solution

The answer panel has winner and the naive version side by side, plus sample boards for a row, a column, a diagonal, a game in progress, a draw and a full board that is also a win. Press Run to see the output.

The answer

const LINES = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],       // rows
  [0, 3, 6], [1, 4, 7], [2, 5, 8],       // columns
  [0, 4, 8], [2, 4, 6],                  // diagonals
];
function winner(board) {
  for (const [a, b, c] of LINES) {
    const mark = board[a];
    if (mark && mark === board[b] && mark === board[c]) return mark;
  }
  return board.every((cell) => cell) ? 'draw' : null;
}
// The same loop without the occupancy check, to show what it was for.
function naive(board) {
  for (const [a, b, c] of LINES) {
    if (board[a] === board[b] && board[b] === board[c]) return board[a];
  }
  return null;
}
const empty = Array(9).fill('');
const row = ['X', 'X', 'X', 'O', 'O', '', '', '', ''];
const column = ['X', 'O', '', 'X', 'O', '', '', 'O', ''];
const diagonal = ['X', 'O', 'O', '', 'X', '', '', '', 'X'];
const playing = ['X', 'O', '', '', '', '', '', '', ''];
const drawn = ['X', 'O', 'X', 'X', 'O', 'O', 'O', 'X', 'X'];
const wonAndFull = ['X', 'X', 'X', 'O', 'O', 'X', 'O', 'X', 'O'];
console.log('row', winner(row), '/ column', winner(column), '/ diagonal', winner(diagonal));
console.log('empty board, naive version:', JSON.stringify(naive(empty)));

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('a completed row wins', winner(row), 'X');
test('a completed column wins', winner(column), 'O');
test('so does a diagonal', winner(diagonal), 'X');
test('an unfinished board is neither a win nor a draw', winner(playing), null);
test('a full board with no line is a draw', winner(drawn), 'draw');
test('a full board with a line is still a win', winner(wonAndFull), 'X');
test('an empty board is undecided', winner(empty), null);
test('but without the occupancy check three blanks are a line', naive(empty), '');
test('there are eight lines and every cell is on one', [LINES.length, new Set(LINES.flat()).size], [8, 9]);

if (mark && ...) is the entire difficulty. Three empty cells satisfy board[a] === board[b] === board[c], so the check without it returns '' for an empty board — falsy, so if (naive(board)) happens to behave, which is worse than failing: the function returns a winner of '' and the bug survives until someone renders it or compares it to null. Ask whether the cell is occupied before asking whether the line matches.

The other ordering that matters is win before draw. A full board can contain a winning line, so checking "every cell filled" first would report a draw for a won game — the wonAndFull assertion is there to keep that fixed. Three distinct outcomes need three distinct values, so this returns a mark, 'draw', or null for still playing; folding "no winner yet" and "drawn" into one falsy answer is how a game announces a draw on move two. Listing the eight lines as data rather than writing eight ifs is what keeps the function four lines long and makes it trivially extensible to a 4×4 board.

Common mistakes

  • Comparing the three cells without checking they are filled. Three blanks are equal, so an empty board "wins".
  • Checking for a full board before checking the lines. The last move can fill the board and win at the same time.
  • Using one falsy value for both "draw" and "still playing". The game can't tell them apart and ends too early.

Try it yourself

  1. Change winner to return the winning line as well, like { mark: 'X', line: [0, 1, 2] }, so the game can highlight it.
  2. Write nextPlayer(board): X moves first, so count the marks to decide whose turn it is.
  3. Build the eight lines with loops instead of writing them out, then try a 4 by 4 board where you need four in a row.

Keep practising

Newsletter

New writing, when it lands.

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