Need help understanding React Tic Tac Toe "Winner" function

Need help understanding React Tic Tac Toe "Winner" function
0.0 0


Can someone please help me understand the “Winner” helper function from the React Tic Tac Toe tutorial?

This is taken from the official React tutorial. The problem I have is understand the for loop. Thanks.

function calculateWinner(squares) {
  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],
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
  return null;



First, calculateWinner() function, declares a multidimensional array ‘lines’, that holds all the winning combinations.

Second, a ‘for’ loop iterate through all the combinations, and adds the board’s squares indexes in constants ‘a’, ‘b’ and ‘c’.

Finally, and ‘if’ conditional statement will compare the current combination of the iteration with the board’s clicked squares combinations, and if there is a match, it returns the current combination, otherwise it returns null.

This is my first time on this forum. Hope I could help you.


It didn’t help :frowning:

But I did managed to figure out while I was showering. The test is on the value or the props. If the value of a, b, c are the same, return the value of a (either X or O).



I was confused at first too, but breaking it down everything makes sense.

See fiddle with detailed explanation: