The While Loop

I can’t really understand what does the program in this exercise do.

https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/while

Can someone explain it?

Thank you in advance :slight_smile:

Hi there,

Let’s look at the code.

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

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

While currentCard is not equal to (!=) ‘spade’ execute xyz code
The code will keep executing until currentCade = ‘spade’


Let us examine what is happening within the while statement.
currentCard = cards[Math.floor(Math.random() * 4)];
console.log(currentCard);

(1) Math.random() * 4 is generating a random number 0 >= || < 1 and then multiplies it by 4.
(2) Math.floor is then taking that random number and rounding it down to the nearest whole number.
(3) Depending on the number returned, the value at that position in the array ‘cards’ is selected
(4) currentCard is set to that value
(5) The value of currentCard is logged to the console

Now, let us examine an example.

(1) currentCard is currently set as an empty variable, so the code within the while loop will execute.

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

(2) Let us say that Math.random() generates the number 0.586

currentCard = cards[Math.floor(0.586 * 4)];
console.log(currentCard);

(3) 0.586 * 4 returns 2.384

currentCard = cards[Math.floor(2.384)];
console.log(currentCard);

(4) Math.floor() takes 2.384 and then rounds it down to 2

currentCard = cards[2];
console.log(currentCard);

(5) cards[2] accesses the item at position 2 and returns ‘heart’ as the value
(Remember: The first item’s position in an array is 0. ‘diamond’ = 0; ‘spade’ = 1; ‘heart’ = 2; ‘club’ = 3)

(6) currentCard is set to ‘heart’ and ‘heart’ is logged to the console

currentCard = 'heart';
console.log(currentCard);

(7) But ‘heart’ is not equal to ‘spade’, so the code within the while loop will execute again.


Now let's say that when the code runs again, Math.random() generates 0.428
currentCard = cards[Math.floor(0.428 * 4)]
currentCard = cards[Math.floor(1.712)]
currentCard = cards[1]
currentCard = 'spade'
console.log(currentCard)

This time, ‘spade’ is logged to the console and because ‘spade’ is logged to the console, the code will not execute again.

Does this make sense?

2 Likes