A Loop Question

Hello everyone. I have a quick question about loops. Here is an example:

const cards = [‘diamond’, ‘spade’, ‘heart’, ‘club’];

// Write your code below

let currentCard = ‘’;

while (currentCard != ‘spade’) {

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



In this code wouldn’t currentCard = cards[Math.floor(Math.random() * 4)]; output a number from 1-4, yet the array list [‘diamond’, ‘spade’, ‘heart’, ‘club’] would be 0-3? how does it read the array list correctly? I apologize if this is silly question. I would just like to understand.

Math.random() generates a random number between 0 and 1, exclusive. So that means the lowest number it can generate is 0, and the highest is akin to 0.999999999…. When you multiply that by four, you can’t get a number that is equal to 4, or above 4. Then, you use Math.Floor(), which rounds any number down. So even if Math.random()*4 equals 3.999, using Math.Floor() on that rounds it down to 3. So the maximum number you can get from Math.Floor(Math.random()*4) is 3.

I hope this helps!

1 Like

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