FAQ: Loops - The While Loop

Not only do the courses need to be re-reviewed for absurd and illegible use of English… but these forums require scrolling past 2 or 3 years of posts before being able to see anything current or post ?!

THIS PLACE IS A JOKE!

Hello!
I’ve been trying to understand the difference between for and while loops for a while but didn’t succeed.
I can’t see any difference between the two. I can see that we only breaks the syntax of the for loop to be a while loop.

In the course examples:

// A for loop that prints 1, 2, and 3
for (let counterOne = 1; counterOne < 4; counterOne++){
console.log(counterOne);
}

// A while loop that prints 1, 2, and 3
let counterTwo = 1;
while (counterTwo < 4) {
console.log(counterTwo);
counterTwo++;
}

Both have the same syntax but different arrangement.
Now I’ve read that we use the while loop, unlike the for loop, when we want a loop to execute an undetermined number of times. But even in the while loop we have to write a condition that determines when the loop should stop, therefore if we are telling the while loop to execute starting 0 (as a var) and while var < 1000, to add 1 to the var (var++) then we know that the number of repetitions will be 1000 loops.
Note: if we didn’t define a condition in the while loop we will have an infinite loop (a bad practice). So as long as we are defining a condition in the while loop, then we know the number of repetitions.
So what’s the difference between while and for loops

1 Like

When there are a fixed number of iterations there is not much difference, since the while loop will have an incrementing (or decrementing) counter. In this case, a for loop might be a better choice.

Now, when there is an indefinite number of iterations, the while loop is the one to reach for, especially if there is no counting at all, only testing for a qualifying condition.

while (condition) {
    //  run zero or more iterations
    //  code
}

do {
    //  run at least one iteration
    //  code
} while (condition)

By indefinite we could also mean, infinite, such as a loop that doesn’t end until we end the session (stop the program).

while (true) {
    //  code
    if (condition) {
        break
    }
}
1 Like

This is what makes it clear for me. Thank you so much!

1 Like

Hello guys,

I finished the instructions and the code seems fine(i have green ticks on all the instructions), but I have a question about the printed results. When i execute the script i am getting random results as i expected but at times i am getting more than 4 results, or lower than 4 results.
Can someone explain why ? Shouldn’t be always 4?

My code:

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)

};

*** EDIT: regarding the results, as i though more about it, since the random number will be a single number, should the array only print one value only ?

Short answer, no. There is no way to predict what the random number will be. Since the solution set is so small (four numbers) it is not unlikely that a 1 will be returned after a small number of iterations, but it is also not unlikely that it could take more than four iterations.

1 Like

thank you for the answer, could you please see the edited part at the bottom ?
[
*** EDIT: regarding the results, as i though more about it, since the random number will be a single number, should the array only print one value only ?

]
Why i am getting more than one items returned from the array since the random number is a single one ?

It is inside a loop for which the breaking condition is ‘spade’ (index 1). The loop runs until that condition arises, which is not predictable, only inevitable.

1 Like

Okay, yeah this seems the logic behind it, thank you Roy :slight_smile:

1 Like

Thank you! Your explanation helped me process this!

Two questions regarding the code below:

  • Why do we not need to add an increment to this while loop? Is it because the variable has no value or because we do not need to increment in order to reach the stopping condition because the stopping condition is ‘spade’?

  • Why does it loop infinitely when I do add an increment? Is it searching for the variable or generating random numbers and incrementing them endlessly?

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);

}

Hello guys,
I finished the instructions and I wanted to try and re-write the loop. Instead multiplying Math.random() by 4, I wanted to multiply by the arrays length, but the code does not work. Can someone explain were I went wrong?

Thank you.

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

while(currentCard!==‘spades’){
currentCard = cards[Math.floor(Math.random()*cards.length-1)]
console.log(currentCard)
}

Two issues:

  • Your condition is while (currentCard !== 'spades'), but currentCard will never equal 'spades' because cards has element 'spade' not 'spades'. The condition needs to be corrected to while (currentCard !== 'spade')

  • Math.random() returns a floating point number in the interval [0, 1) i.e. in the interval 0 ≤ x < 1. In the original code, we multiplied the number returned by Math.random() by 4 to get a floating point number in the interval [0, 4). Then we floored this number so that the result would be one of the values 0, 1, 2, 3. In your code, you have (Math.random()*cards.length() - 1), this will return a floating point number in the interval [-1,3) and when floored, the result will be one of the integers -1, 0, 1, 2. But cards[-1] will be undefined because it is not a valid index in the range 0-3. It should work if you edit your code to:

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

Since cards.length() is 4, so you eventually end up with one of the integers 0, 1, 2, 3 as intended.

1 Like

Thank you. This really helped.

1 Like

I have a question on the console result, why we get varying result every time we run the program.
why some time 3, why some time 6 or 9, how is this program running.

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)
}

Hey!

Quick question regarding this exercise. When running through the steps, my brain immediately wrote out:

let currentCard;
while (currentCard !== cards[1]) {
  currentCard = cards[Math.floor(Math.random() * 4)];
}

I quickly figured out that

while (currentCard !== 'spade')

was the proper solution but it made me think, why can you not reference the Array rather than typing the string you want currentCard to match?

Thanks in advance!

const cards = ['diamond', 'spade', 'heart', 'club'];
while (currentCard !== cards[1]) {

That will work fine since 'spade' is the second element of the cards array.

If the exercise doesn’t accept that as a solution, it is probably because Codecademy’s automated grader may not have been configured to accept an alternate solution to (currentCard !== 'spade'). But other than that, there is nothing invalid about your solution. There may be pros and cons to both versions. One argument may be that (currentCard !== 'spade') doesn’t require any person reading the code to have to look through the cards array to determine which suit is intended in the condition. Also, if the order of elements in the array is somehow shuffled, then 'spade' may no longer be the second element of the array. However, there can be arguments made in favor of the (currentCard !== cards[1]) version as well.

In terms of syntax or logic, both approaches are valid and specify the same condition.

Ahh yes, I had not considered the Array possibly being mutated causing problems with the code later on. That is good to know, and good to know it provoked me to think of a solution outside of the lesson! Thanks for the info!

hi, i am a beiginner. Could someone tell me why it needs to add ’ ! ’ before currentCard?

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);

}

The subject of logic will come up soon if it has not already. In a nutshell, we have three operators that stand for the logical operations, AND, OR and NOT,

&&
||
!

respectively. AND and OR are for another conversation. We’re only interested in NOT, for the present.

The NOT operation is a boolean toggle. We know that to toggle a light switch we set it to its opposite position. What is OFF switches to ON; and, what is ON switches to OFF. That is what toggling is.

In the case of the two boolean primitives, true and false,

! true   =>  false

! false  =>  true

See how the boolean is toggled? We can apply this further to expressions whose value tends toward truthiness, or tends toward falsiness.

""
''
``
0
undefined
null

Above all those expressions are falsy. When we apply the NOT operator to them the yield is always, true. Try it:

console.log(! 0)

It will display, true. Toggling of anything, whether truthy of falsy will always result in a boolean, false or true in that order.

One important thing to note about the NOT operator (!) is that it only takes one operand, which is on its right side. You may see this referred to as a unary operator which is the class of operators with only one operand.

! x === y

is not the same as,

! (x === y)

The first will evaluate ! x before it evaluates ===. NOT has operator precedence over identity or equality so that operation comes first. Say that x is a truthy value,

x = 1

That will result in,

false === y

Unless y is actually, false the identity does not hold and the expression yields, false.

Now let’s let,

y = 1

and evaluate the second example,

! (x === y)    <== note the parentheses

It will also be false. Since x is identical to y (truthy) once toggled gives false. We changed the order of operation so that NOT is applied after ===. The above expression is the equivalent of,

x !== y

In the above, !== is the toggling of the identity operator, rather than a boolean, but it is akin to boolean logic. It means, ‘not identical to’. The one in your code example means, ‘not equal to’ which in JS involves the extra step of coercion owing to loose type matching, which is also for another conversation.