# Understanding 6. while loops with card suits

#1

I finished the exercise, but I'm wondering how the program gets suits out of this piece of code. The instructions say to "create a random number between 0 and 3 and put it in a variable named randomNumber" but where does that happen?
To me it looks like a randomly generated number is being multiplied by four, set to its integer, and passed to a list item of cards. Am I misunderstanding Math.floor or how operators work with Math.random or something?

``````var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
console.log(currentCard);
var randomNumber = Math.floor(Math.random() * 4);
currentCard = cards[randomNumber];
}``````

#2

create a random number between 0 and 3 and put it in a variable named randomNumber" but where does that happen?

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

Math.random will generate a random number between 0.000etc up to 3.999etc and Math.floor will round it down to the nearest integer, which is why you get 0, 1, 2 or 3.

#3

So does *4 make it "up to four" instead of "multiplied by four"?

#4

Not quite,

What Math.random really does is give you a random number between 0 and 1.
You then multiply that number by 4.

e.g.
Math.random() = 0.7898638342881765
0.7898638342881765 * 4 = 3.159455337152706

Edit: what you could do is play around with it in the console.
Set this up:

``````var calculation = Math.random();
console.log(calculation);``````

and keep hitting "Run". You can then add Math.random() * 4, and then Math.floor to see how they work together.

#5

I was missing the part about Math.random output being between 0 and 1, it makes sense now. Thanks!

#6

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