Dont know why my loop is running indefinitely


I really dont know why my loop is running indefinitely

var cards =['Diamond','Spade','Heart','Club'];
var currentCard=('Heart');
var randomNumber=2;


can someone help me?

JavaScript - Card Flip until get 'Spade'

Okay. Sorry to hear. Try randomNumber =1 and not 2.


Two things,

  1. We do not use var inside a loop. The variable should be declared outside the loop, then set or reset in the loop.
  2. Setting a literal when it should be random is the cause of the infinite loop. It should not be a constant.

    randomNumber = Math.floor(Math.random() * cards.length);


I thought of the math random too. What was the instructions?


I see the author instructed the var randomNumber statement be inside the loop. It's not hurting anything, but I disagree. No matter.

var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
currentCard = "Heart";
var randomNumber;
while (currentCard !== 'Spade') {
  randomNumber = Math.floor(Math.random() * cards.length);
  currentCard = cards[randomNumber];

The instructions do not ask us to log anything inside the loop. When the code is run the only thing that should display is, Spade.


As suggested already, the mistake might be on the definition of randomNumber. If it's set to 2, it's not quite random... and will loop "Hearts" forever.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.