Check 8 win patterns: [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]. For each pattern, if board[a] === board[b] === board[c] and board[a] is not null, that player wins.
How to Build a Tic-Tac-Toe Game in an Interview
How do you detect a win in tic-tac-toe in JavaScript?
The answer
More FAQs in How to Build a Tic-Tac-Toe Game in an Interview
Create a 3x3 grid. Use an array of 9 elements for the board. Alternate players (X/O). After each move, check 8 win patterns (3 rows, 3 columns, 2 diagonals). Detect draw when all cells are filled. Add reset and score tracking.
Check if all cells are filled (board.every(cell => cell !== null)) and no winner was detected. If so, it is a draw. Check for a win first, then check for a draw.
Clicking an already-filled cell (ignore), clicking after game over (ignore), highlighting the winning cells, score tracking (X wins, O wins, draws), and reset button to start a new game.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.