Dont know why my loop is running indefinitely


#1

I really dont know why my loop is running indefinitely

var cards =['Diamond','Spade','Heart','Club'];
var currentCard=('Heart');
while(currentCard!=='Spade'){
console.log(currentCard);
var randomNumber=2;
currentCard=cards[randomNumber];

}
console.log(currentCard);

can someone help me?


JavaScript - Card Flip until get 'Spade'
#2

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


#3

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);


#4

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


#5

https://www.codecademy.com/en/courses/learn-javascript/lessons/loops/exercises/while

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];
}
console.log(currentCard);

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.


#6

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.


#7

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