Why does this while loop print the != condition?


#1
const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;

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

My understanding of this is that the code should only execute if currentCard does not equal ‘spade’. Therefore, if currentCard == ‘spade’, nothing should print to the console. However, when I run the code, I always get ‘spade’ as my last log. Why? How can I get the behavior I was expecting?


#2

Consider the order of your code…

currentCard is always selected, then immediately printed, regardless of its value. It always prints spade as the final card, because it runs until it finds that card. When it finds that card (your condition in the loop), it stops, but it has ALREADY printed. Simple fix; switch the two lines around:

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

#3

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