While loop never seems to produce the result I need and instead acts a little crazy


#1

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

My insane code is creating insane results. I passed the lesson fine, but this seems a bit zany. Spade is never printed to the console and instead I get the ending console.log printed and one or more of the other array items. It's really quite bananas.

Any help would be appreciated. Thanks.

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

while (currentCard !== 'Spade') {
  console.log(currentCard);
  
  var randomNumber =
Math.floor(Math.random() * 4);
  
 currentCard = cards[randomNumber];
}

console.log('Found a spade!');


#2

We should not use var inside a loop. The variable is declared before the loop so just set it inside. Be sure the assignment is on one line, only. Otherwise your code looks fine.


#3

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