Workshop › Tic-tac-toe › Step 25 of 33
Now the computer will play O. Its first version is simple: make a list of the free cells and pick one at random.
```js
function computerMove(cells) {
const free = []
cells.forEach((cell, index) => {
if (cell === '') free.push(index)
})
const random = free[Math.floor(Math.random() * free.length)]
return random
}
```free starts as an empty array; free.push(index) adds each empty cell's number to its end.Math.random() is a random number from 0 up to (not including) 1. Times free.length, rounded down, it is a
valid position in free.Under outcome, leave an empty line and write computerMove (above function play). Press Run.
Skills: Arrays and objects, Functions
← Click to play again The computer answers →