Could someone just explain what's happening here? (While loop exercise)


#1

https://www.codecademy.com/courses/learn-javascript/lessons/loops/exercises/while?action=lesson_resume

I just don’t understand why this is doing what it’s doing, I get how to do it and it’s running fine, but the order of things and the fact that currentCard equals ‘Heart’ the first time every time, but then goes on to become a random string from the other variable is what confuses me… Mainly because I feel like since the math functions are below the console.log in the ‘while’ loop, that it would override even the first run at currentCard, but it doesn’t and the first time being ‘Heart’ remains constant. I don’t know, I think the exercise doesn’t really explain any of this very well and just kind of holds your hand telling you what to do instead of really letting you know what’s going on in the function…



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

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

console.log('Found a spade!')





#2

there is a good reason console.log() is before you pick a new card, you want to inform the user of the current card, then update to a new card.

then the next iteration of the loop, you display the newly picked card and then select a new card


#3

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