Why does this while loop execute spade even though it is a stopping condition?

Consider the following code snippet:

const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;
while (currentCard !== 'spade'){
  currentCard = cards[Math.floor(Math.random() * 4)];
  console.log(currentCard);
}

When this code block runs, in the result the last word will be spade . It happens even though it is in stopping condition.

Can anyone tell me why this is happening

Thanks in Advance!

Hi @darkphoenix007
this is the order of how your code is run:

  1. You check if the condition is fulfilled: currentCard === undefined → true
  2. You reassign the the currentCard: Can be spade, but the condition check was prior to this
  3. You log the currentCard: e.g. spade
  4. You check the condition again: If the previous assignment was spade, the condition is false, but the card was already logged.

Ok now I understood. But I have one more doubt. Why does the

Does not evaluate to 4?

No. This generates numbers from 0 to 3.
Example:

const random = Math.random(); // 0.9999999999999999
const randomMultiplied = random * 4; // 3.9999999999999996
console.log(Math.floor(randomMultiplied)); // 3
card[0] // 'diamond'
card[1] // 'spade'
card[2] // 'heart'
card[3] // 'club'