JavaScript - Card Flip until get 'Spade'


#1

Could someone help me understand this code?

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

var currentCard = 'Heart';

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

  currentCard = cards[randomNumber];
}

console.log('The program found a ' + currentCard);

Here's the link to the lesson.. Don't know why I've to redo JavaScript anyhow...


#2

The above line generates an integer in the range 0..3 which correspond to the indexes of the cards array. By randomly generating it we cannot predict which card will be next.

We can see that the loop will run indefinitely until a Spade is happened upon (index 1).


#3

So the randomization jumbles the cards array and assigns each card a number/index and will run until the currentCard is a spade / the random number of ?? 3?

----- Reply message -----


#4

The random number is an index. The array remains in the order in which it is written. cards[1] will always be 'Spade'.

This simulates a shuffle, without actually shuffling. Essentially we are pulling a card and replacing it if it is not a Spade.


#5

Perfect. Now I understand! Waw. Thanks soo much. I can now rest in peace. :wink:

----- Reply message -----


#6

This was pretty challenging. And I am not sure if I was confuse or reading it wrong. I got to understand this language more because its getting more complex. You know.. Thanks for the helps guys. This thread got me to understand this a lot more.


#7

Keep it going yaw!

----- Reply message -----


#8

4 posts were split to a new topic: Dont know why my loop is running indefinitely