0

I am trying to code a game of snap in JS. When the cards are the same, the console will log 'SNAP!' OK, but it will not stop. Am I adding the break; in at the wrong part?

for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
  for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
    if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
      console.log('SNAP!');
      break;
    } else {
      console.log('Go again...');
    }
  }
};
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
James
  • 106
  • 7
  • 1
    Consider putting this double for loop by itself in an appropriately named function and using `return` instead of `break`. You're only breaking out of the inner loop. – Patrick Roberts Mar 07 '19 at 22:45

1 Answers1

0

The break will stop only the second for, meaning this one:

for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++)

The best option is to set a flag, initially false, and then set it to true besides making the loop break. Then if the flag is set to true, break also the first for.

var flag = false;
for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
    for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
        if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
            console.log('SNAP!');
            flag = true;
            break;
        } else {
            console.log('Go again...');
        }
    }
    if (flag) {
       break;
  }
};
rusito23
  • 995
  • 8
  • 20
  • Thanks so much, I've tried this, but it still keeps running. I want it to only log Go again until the cards match. When they match, SNAP! is to be printed and then no more loops. Instead, it keeps going. – James Mar 07 '19 at 23:21
  • I've cracked it! I placed the flag if statement before the 'Go again...' console log. Thank you very much for your help, sir! – James Mar 07 '19 at 23:23
  • glad to help!! good luck – rusito23 Mar 08 '19 at 13:34