6/8 While Loops - Explanation of added code?

Hello All,

I just finished Learn Javascript 7 Loops - While Loops 6/8

Instruction #4 asks us to add the following code

currentCard = cards[Math.floor(Math.random() * 4)];

However, there is no explanation how this code works or what it is doing. I understand conceptually Math.floor and Math.random, but I don’t understand how they are working together and why it is multiplied by 4

Anybody provide a rundown of this code?


we have 4 cards in our array at the indexes: 0, 1, 2, 3

now we want to pick a random card, so we need to generate one of the indexes randomly. This random index can then be used to get a card from the array (using the square brackets)

so math.random generates a random value between 0 and 1 (0 and 1 are not included), so by multiplying this random number by 4 and then flooring, we get: 0, 1, 2, 3. Which is what we need


Makes sense. Thank you for the straightforward explanation!

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