1

I have a recursive loop which for this question I've simplified to the following:

const move = (gameGrid) => {
    if (Math.random() > 0.2) return false;

    let newGameGrid = [...gameGrid];
    return newGameGrid;
}

const play = (initGrid) => {
    for (let player1Move=0; player1Move<9; player1Move++) {
        grid1 = move(initGrid);

        if (!grid1) continue;

        for (let player2Move=0; player2Move<9; player2Move++) {
            // Why is grid1 sometimes false here???
            grid2 = move(grid1);

            if (!grid2) continue;
            play(grid2);
        }
    }
}

play([])

What you'll notice if you run this is that sometimes in the second play() loop the call to move(grid1) fails at [...gameGrid] because grid1 is false. However, this should be impossible because before the second loop executes grid1 is checked for a false value.

Any ideas what I'm missing here? I'm guessing grid1 is being overwritten but I'm not sure how or where.

3
  • Unless I'm missing something but doesn't if (!grid1) continue; basically state: if grid1 is false, continue to the for loop? Commented Oct 12, 2020 at 21:06
  • 2
    @imvain2 it's skipping the current iteration but continues looping. Similar to how break; also stops the current iteration but with continue you do still stay in the loop. Commented Oct 12, 2020 at 21:07
  • @imvain2 I had to look it up too: continue on MDN Commented Oct 12, 2020 at 21:09

1 Answer 1

1

Not sure what are you tring to achieve, but looks as you haven't defined grid1 and grid2 in scope they are shared between multiple calls in global scope during recursive function calls. Use 'let' or 'const` to define both variables in scope and that will fix issue you mentioned.

const move = (gameGrid) => {
  if (Math.random() > 0.2) return false;

  let newGameGrid = [...gameGrid];
  return newGameGrid;
}

const play = (initGrid) => {
  for (let player1Move = 0; player1Move < 9; player1Move++) {
    let grid1 = move(initGrid);

    if (!grid1) continue;

    for (let player2Move = 0; player2Move < 9; player2Move++) {
      // Why is grid1 sometimes false here???
      let grid2 = move(grid1);

      if (!grid2) continue;
      play(grid2);
    }
  }
}

play([])

Sign up to request clarification or add additional context in comments.

1 Comment

How embarrassing, I have been looking at this for over an hour. How the hell did I miss that. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.