FAQ: Loops - The While Loop

Sorry. The question is pretty silly. It is said that it does not give any output.

:sweat_smile: :sweat_smile: :sweat_smile:

You do the code and that’s the log you recive!!!
:rofl: :rofl: :joy:

I am having trouble understanding what * 4 does within the following code block:

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

I have probably just forgotten something relatively simple from a previous lesson, but I’ve tried looking it up and going through it and can’t understand exactly how this code block works.

Full code for context:

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

// Write your code below

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

Cheers.

So that tells us this is not your own code or this question wouldn’t have come up. First rule of coding is to never use code you couldn’t write yourself. Reverse engineering is not the best (or easiest) way to learn. It’s called engineering because the ones reversing it are usually knowledgeable enough to decipher the finer points and hidden secrets.

That said, let’s first examine the array. How many elements does it have? Four. So we need to generate four possible outcomes with Random.

Math.random() generates a float that can be anywhere from 0, inclusive, to 1, excluded. That is, 0 to 0.999…, just never 1.

We want to break that generated value into four intervals, hence the multiplier 4.

 Math.random() * 4

That will give us a number between 0 and 3.999… which when we floor it will be 0, 1, 2 or 3, the indices for the above array.

Thanks for the explanation. I totally understand where I went wrong, I forgot that Math.random() generates a random float between 0 and 0.999, rather than an integer, and the purpose of the 4 confused me.

I knew it was something basic that I was getting wrong, but couldn’t seem to figure out what. I took a break after completing the “Getting More Advanced with Design” segment of the Web Design Career Path to focus on nailing some of the more advanced CSS that I had just learned and in the process had forgotten some more of the basic Javascript. So my bad.

Appreciate the help.

1 Like

THANK YOU so much for this.this just SAVED my life, I was going crazy. Read almost every answer possible and just didn’t quite get it. :blush:

Every time the loop runs it prints to the console. Therefore the number of lines printed to the console is the number of times the loop ran.

If the console just says :

spade

Then the loop ran once and quite.

If the console says :

heart
spade

Then the loop ran two times and quit, because it printed to the console twice.

Let’s walk through what is happening during each loop.

  1. The currentCard variable is compared to ‘spade’. Since currentCard is undefined and the statement is true everything in the braces runs. A random number is generated and the item at that location in the array is printed to the console.

  2. Back at the while loop it compares the currentCard that was just printed to the console to 'spade'. If currentCard is 'spade'. The loop doesn’t run again and all you have is spade in the console.

  3. If the card is not 'spade'. A random number is generated and the item at that location in the array is printed to the console.

  4. This will continue until 'spade' is printed to the console. When this happens the while loop condition becomes false and the loop stops.

This is a good example on how and where to console.log() in your loops. It really doesn’t matter where you put the console.log() inside a single loop like this(as long as it is inside the loop). It will always print something to the console every time loop runs. Try putting the console.log() before the number generator. This will show you that the currentCard is undefined the first run. If 'spade' is generated after that first loop it won’t run again, and only undefined will be printed to the console.

1 Like

Re: How many times does this loop run?

Every time the loop runs it prints to the console. Therefore the number of lines printed to the console is the number of times the loop ran.

If the console just says :

spade

Then the loop ran once and quite.

If the console says :

heart
spade

Then the loop ran two times and quit, because it printed to the console twice.

Let’s walk through what is happening during each loop.

  1. The currentCard variable is compared to ‘spade’. Since currentCard is undefined and the statement is true everything in the braces runs. A random number is generated and the item at that location in the array is printed to the console.

  2. Back at the while loop it compares the currentCard that was just printed to the console to 'spade'. If currentCard is 'spade'. The loop doesn’t run again and all you have is spade in the console.

  3. If the card is not 'spade'. A random number is generated and the item at that location in the array is printed to the console.

  4. This will continue until 'spade' is printed to the console. When this happens the while loop condition becomes false and the loop stops.

This is a good example on how and where to console.log() in your loops. It really doesn’t matter where you put the console.log() inside a single loop like this(as long as it is inside the loop). It will always print something to the console every time loop runs. Try putting the console.log() before the number generator. This will show you that the currentCard is undefined the first run. If 'spade' is generated after that first loop it won’t run again, and only undefined will be printed to the console.

1 Like

I still don’t really understand when I should use a for loop and when I should use a while loop. This lesson states:

The syntax of a for loop is ideal when we know how many times the loop should run, but we don’t always know this in advance. Think of eating like a while loop: when you start taking bites, you don’t know the exact number you’ll need to become full. Rather you’ll eat while you’re hungry. In situations when we want a loop to execute an undetermined number of times, while loops are the best choice

However, I kind of feel like both loops act exactly the same! Take these examples:

for (let i = 0; i < 10; i++) {
  console.log(i);
}
let i = 0;

while (i < 10) {
  console.log(i);
  i++;
}
Output:
 1
 2
 3
 4
 5
 6
 7
 8
 9

In both cases, the output is the same. The only differences I can see is that the declaration and initialization of the iterator variable takes place in a for loop but outside a while loop and that the incrementation of the iterator variable takes place in the initializing statement of the for loop but in the body of the while loop

I’m also aware that developers tend to prefer for loops. I can guess that it’s because the iterator variable is locally scoped, right?

While is very opened. We use it in cases where the length is unknown, or where conditions may vary within the loop.

One difference is that for loops are slightly less prone to being infinite loops. Otherwise, they perform the same function. They repeat a series of steps until a stop condition is met. Here’s a for loop that is almost exactly a while loop:

let count = 0;
for(;count < 10;) {
  console.log("Hello, World!");
  count++; //leave this line out, and you have an infinite loop
}
1 Like

And here’s a while loop based on condition, not count…

let x = 1
while (x > 0.2) {
  x = Math.random()
  console.log(Math.floor(x * 10 + 1))
}

And another from one of the lessons…

const suits = ['hearts', 'clubs', 'diamonds', 'spades']
let suit;
while (suit !== 'spades') {
    suit = suits[Math.floor(Math.random() * 4)]
    console.log(suit)
}

Why couldn’t you just write:

const suits = ['hearts', 'clubs', 'diamonds', 'spades']

for (let suit; suit !== 'spades';) {
    suit = suits[Math.floor(Math.random() * 4)]
    console.log(suit)
}
2 Likes

Why not? No reason. The sky is the limit in terms of what we can and cannot do, without going into the things we should not do or the gray area of using a non-standard approach to a standard problem. This example falls into the gray area, as valid as it may be.

2 Likes

So it’s just a matter of non-standard approaches and best practices?

I wouldn’t stress the best practices aspect in this case. There is no practice guideline being broken here. The code is valid and it works as expected. It’s just a little off the beaten path.

1 Like

declare your currentCard variable without assigning any value, just
let currentCard;

const cards = [‘diamond’, ‘spade’, ‘heart’, ‘club’];
let currentCard;
while (currentCard !== cards[1]) {
currentCard = cards[Math.floor(Math.random() * 4)];
console.log(currentCard);
}

why did i have to write my condition to be (currentCard !==‘spade’) for it to pass and not while (currentCard !== cards[1]) ? although both gave me the same result

Because that is the way the author intended us to write it. And, it makes the most sense. ‘spade’ is explicit; card[1] is not. If the list gets jumbled it will no longer be what we’re looking for.

Alright! duly noted.

1 Like