Build the game around a nine-cell array, a current player, and a result. Each valid move updates the array, checks for a winning line or draw, and then changes the player if play continues. The code for tic tac toe below keeps those rules separate from the browser display, so you can test the JavaScript game by playing it or by calling the rule functions directly.
Tic Tac Toe JavaScript: A Complete Example
Save the following as index.html and open it in a browser. Two people take turns on the same device; X always starts. Each square is a button, so it works with a keyboard as well as a pointer. The status line announces whose turn it is and reports the outcome.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tic tac toe</title>
<style>
body { font-family: sans-serif; margin: 2rem; }
#board { display: grid; grid-template-columns: repeat(3, 4rem); gap: .25rem; }
#board button { width: 4rem; height: 4rem; font-size: 2rem; }
#restart { margin-top: 1rem; }
</style>
</head>
<body>
<h1>Tic tac toe</h1>
<p id="status" aria-live="polite"></p>
<div id="board" aria-label="Game board"></div>
<button id="restart" type="button">Restart</button>
<script>
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 newGame() {
return { board: Array(9).fill(""), player: "X", result: "" };
}
function outcome(board) {
for (const [a, b, c] of lines) {
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
return board[a];
}
}
return board.every(cell => cell !== "") ? "draw" : "";
}
function move(game, index) {
if (game.result || !Number.isInteger(index) || index < 0 ||
index > 8 || game.board[index] !== "") return game;
const board = [...game.board];
board[index] = game.player;
const result = outcome(board);
return {
board,
player: result ? game.player : (game.player === "X" ? "O" : "X"),
result
};
}
const boardElement = document.querySelector("#board");
const status = document.querySelector("#status");
let game = newGame();
const buttons = Array.from({ length: 9 }, (_, index) => {
const button = document.createElement("button");
button.type = "button";
button.addEventListener("click", () => {
game = move(game, index);
render();
});
boardElement.append(button);
return button;
});
function render() {
buttons.forEach((button, index) => {
const mark = game.board[index];
button.textContent = mark;
button.setAttribute("aria-label", `Square ${index + 1}: ${mark || "empty"}`);
});
status.textContent = game.result === "draw" ? "Draw!" :
game.result ? `${game.result} wins!` : `${game.player}'s turn`;
}
document.querySelector("#restart").addEventListener("click", () => {
game = newGame();
render();
});
render();
</script>
</body>
</html>
The tic tac toe code creates nine buttons once, then updates their labels from the current state. Pressing an occupied square leaves the board and player unchanged. After a win or draw, later clicks also leave the result intact until Restart creates a fresh game.
Model the board and the turns
The array stores the board in reading order: indexes 0, 1, and 2 are the top row, and 6, 7, and 8 are the bottom row. An empty string means a square is available. X and O are ordinary strings, so the display can use the same values as the rules.
In this tic tac toe javascript example, newGame() returns a new array, sets X as the first player, and clears the result. Keeping the result in state matters: an apparently empty square can remain after a win, but it is no longer a legal move. A separate flag is unnecessary because a nonempty result already tells the move function that the round has ended.
The tic tac toe code checks an index before modifying anything. It rejects a finished game, a non-integer or out-of-range index, and an occupied square. When a move is valid, it copies the array before placing the mark. Returning a new state makes it easier to compare the old and new positions while testing. In the tic tac toe code, an invalid move returns the original state, including the current player. That makes a second click on the same square a no-op instead of secretly consuming a turn. The browser handler can render after either case because the state remains the single source of truth.
Check all eight lines
There are three rows, three columns, and two diagonals. The lines array lists their indexes. For each line, outcome() first requires a nonempty starting cell and then compares all three cells. This prevents three empty squares from being mistaken for a win.
The tic tac toe javascript rules check a win before checking for a full board. That order matters on the ninth move: the final mark can both fill the board and complete a line. If no line wins and every cell is filled, the result is draw. Otherwise an empty result means the game continues, and move() switches the player.
The tic tac toe code represents a win with the winning mark, so the interface can announce either X wins! or O wins!. It keeps the final player unchanged after an outcome, though the display uses the result rather than the player to name the winner. For a larger project you could return richer result data, including the indexes of the winning line.
Keep the display separate from the rules
The game logic does not read a button’s text or write to the page. It receives state and an index, then returns state. render() does the opposite job: it reads state and updates the DOM. This separation lets the same rules support another interface and makes a JavaScript tic tac toe game easier to debug when the display and the board disagree.
The buttons stay focusable, including occupied squares, but the rule function ignores invalid moves. Their accessible labels identify the square and mark, and the live status reports changes. The Restart button replaces all state, then renders the empty board and X’s turn. It does not need to create nine more buttons or attach the listeners again.
Test a win, a draw, and a repeated move
Number the squares from one to nine in reading order for these manual checks. Restart between sequences; the players alternate automatically.
- Win: select
1, 4, 2, 5, 3. X completes the top row. The status should report X as the winner, and a later click should change nothing.
- Draw: select
1, 2, 3, 5, 4, 6, 8, 7, 9. The board fills without a line; the status should say Draw!.
- Repeated move: select
1 twice. The second selection must leave X in that square and keep O as the next player. Then choose another square and confirm O appears.
For a JavaScript version of tic tac toe, also test a column and a diagonal win, then restart after each result. These paths exercise the same line table from different directions. For a direct test of the JavaScript tic tac toe logic, open the browser console and call outcome(["X", "", "O", "X", "O", "", "X", "", ""]). It should return "X" for the first column. An empty array of nine empty strings should return an empty result; use Array(9).fill("") to create it. Try Tab and Enter to confirm that each button can be reached and activated without a mouse.
This tic tac toe game code has no computer opponent or network state; its two players share the same page. Adding either feature would require deciding how those moves reach the same validation function and how the interface handles a delayed or unavailable opponent.
Keep this checklist nearby
- Store nine cells, the active mark, and the result; reset all three for a new round.
- Reject occupied, invalid, and post-game moves before changing state.
- Check eight winning lines before declaring a full board a draw.
- Render from state, announce the result, and test the code for tic tac toe with wins, a draw, and a repeated square.