Card shuffle until it gets spade card


can someone help me understand this code:

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

while (currentCard !== 'Spade') {

var randomNumber = Math.floor(Math.random() * 4);

currentCard = cards[randomNumber];
console.log('Found a Spade');


we have an array with the different card types (diamonds, spade and so on)

Then we select a starting car (heart)

then we loop until we find a spade. In the loop, each iteration of the loop we generate a random number, this number is used as index to pick card from array, causing a random card. once spade is picked, the loop condition becomes false, the loop ends, you inform the user they found a spade


so it means that this code "var randomNumber = Math.floor(Math.random() * 4);
currentCard = cards[randomNumber];"
is for indexing the items in the array only?


no, the random number generated is used as index to retrieve card type from array, given the number generated is random, so is the card picked


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