Search code examples
reactjsfor-loopif-statementreturntic-tac-toe

React tuto tictactoe game - who's the winner - return null inside a for loop


In the tuto of React.dev, i get confused when it comes to tell who is the winner : tutorial tictactoe - part who's the winner

I can't get return winner if i put return null inside the for loop instead of putting it outside, it keeps returning null.

From the line 59 of App.js in my codesandbox

function theWinner(squares) {
 const lists = [
  [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 < lists.length; i++) {
   const [a, b, c] = lists[i];
   if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
     return squares[a];
    }else{
     return null ; 
    }
   }
 }

Thanks for your help.


Solution

  • Your for loop will always exit on its first iteration. This is obviously not what you want.

    While you can stop looking further when you have found a winning line, you should continue looking further when the current 3 cells do not represent a win. So in that case doing a return is premature. You cannot know whether there will be a win elsewhere or not. For that you need to make all iterations of the loop, and only after you have verified all, you can conclude that there are no winning lines.

    So:

    function theWinner(squares) {
      const lists = [
        [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 < lists.length; i++) {
        const [a, b, c] = lists[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
          return squares[a];
        }
      }
      return null; // <-- only now we can know there was no win.
    }