FAQ: Loops - The While Loop

Thanks for the quick answer biirra!
I see my error now :slight_smile:

Edit: I asked a stupid question and found my answer from googling :slight_smile: Thanks!

1 Like

This threw me for a loop :sweat_smile: - jk. But seriously, how was it decided to use ’ 4’, instead of any other number?* Is there a specific reason? I’ve tested the loop with *10, *3, and so on. It seems to work, but also prints ‘undefined’ at times. Running it with *1 will not print to the console.


Ha :slight_smile: When generating the index of the current card, we multiply by 4 here because there are 4 elements in the cards array:

Math.floor(Math.random() * 4)

This will give us numbers from 0 to 3 (explained below). That’s what we need, because cards has 4 elements and array indexes start at 0, so the card indexes run from 0 to 3.

Math.random generates numbers from 0 to something like 0.9999999999999999, while Math.floor rounds numbers down to the nearest integer. So from our code, zero is the minimum number we can get:

Math.floor(Math.random() * 4)
Math.floor(0 * 4)

And three is the maximum:

Math.floor(Math.random() * 4)
Math.floor(0.999... * 4)

If you multiply by a number greater than 4, it will sometimes print undefined because you will generate nonexistent card indexes (like 4, 5, 6, etc.).

If you multiply by 1, on the other hand, you will create an infinite loop. That’s because you will always generate a card index of 0, but the spade card has an index of 1. You’re looping until you find the spade, but that will never happen, so your loop will run forever. I’m guessing nothing printed to the console for you because of some error related to that.


That makes total sense now. And yes, I had the refresh the page several times when running it with ‘*1’ :sweat_smile:.

Basically, in order to generate this task, we must know the length of the array first, right? The reason I tired various options was (1) I was trying to learn what happens, since I wasn’t clear on why 4 was used, and (2) if I didn’t know the specific length of an array. But, I guess that’s a quick line of code to identify the length before executing the task.

Greatly appreciated!


I had the refresh the page several times when running it with ‘*1’ :sweat_smile:

I was fooling around in JSFiddle and managed to hang up my whole browser while testing that part out. :slight_smile:

Yep, we do need to know the array length. But like you indicate, we can just check the length property of the array.

Glad I could help!


Could you please explain what happens? when I pasted this code, the page froze.

It’s not that its fronzen it’s because this piece of code does not do anything visual on the page.

If you press “F12” and you click the “console” tab in the window that pops up you will see the result.
This because console.log(); prints to that tab.

This is also where errors in your code are shown.


I think a more accurate answer to your question:

could be:

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

// Write your code below
let currentCard;
let times = 0;
while (currentCard != ‘spade’) {
currentCard = cards[Math.floor(Math.random() * 4)];
//this output the card picked and the round

I just learned how to do the “for” looping. And the rule was you had to have 3 things between semi-colons.
Now the “while” looping doesn’t require that. So, I’m confused. thank you!

I ran it “successfully” so I can go to next lesson; but I’m unsatisfied. Logging the code produced 6 cards. I think currentCard should only show 1 card?


I’ll give explaining the difference a shot.

The for loop has 3 parts in it's initializing statement:
for (initialize the index variable; index variable stop condition; increment index variable)
for ( let i = 0; i < 3; i++) {
  //The code in this block will be executed 3 times
  //Once for each value of i: 0, 1, 2



The while loop only has a stop condition:

let count = 0;
while (count <= 10) {
  /*The code in this block will repeat until count is greater than 10*/



Hopefully this helps.


It does. Thank you!:grinning:strong text

added some features:

const cards = ["\u2666", "\u2660", "\u2665", "\u2663"];

let currentCard;
let i=0;
while (currentCard != "\u2660") {
  currentCard = cards[Math.floor(Math.random() * 4)];
if (i===1){
    console.log("wow you soo lucky, you picked \u2660 right away");
} else {
  console.log("it took "+i+" times for you to pick spade");

For consistency, why not,

console.log(`it took ${i} tries for you to pick \u2660.`);



what’s the difference between condition while(!(currentCard === ‘spade’)) and while(currentCard != ‘spade’) ?

Very little difference, on the whole. They are both comparisons that yield the same outcome.

not (condition)

will be true if condition is false

 a !== b

will be true if a does not equal b.

I ran the code and got a tick on the box, and was allowed to continue, however my code is wrong. It takes a very long time to load (it did eventually load so I’m not sure if it’s an infinite loop). It also keeps logging to console even after it finds ‘spade’. Here is my code:
const cards = [‘diamond’, ‘spade’, ‘heart’, ‘club’];

// Write your code below
let currentCard=;

while (currentCard[0]!=‘spade’){
currentCard = cards[Math.floor(Math.random()*4)]

Edit: Ok, I fixed it. I made currentCard an array unnecessarily. Not sure exactly what was happening in code though. I guess it was setting, for eg. ‘diamond’ as a string array, rather than the string to check against. This is my fixed code:
const cards = [‘diamond’, ‘spade’, ‘heart’, ‘club’];

// Write your code below
let currentCard;
while (currentCard!=‘spade’){
let tempNum=Math.floor(Math.random()*4)
currentCard = cards[tempNum]

Hello, @ajax5863680087, and welcome to the forums.

This is worth exploring. First you assigned an empty array to currentCard, so in the first iteration of the while loop, the expression currentCard[0] != 'spade') evaluates to true, and the code inside the loop’s { } is executed. The first line of code inside that block reassigns a value to currentCard.
Whereas, currentCard previously pointed to an empty array, it now points to an element of the cards array that was assigned using a randomly generated index. Let’s say it was assigned 'spade'.
console.log(currentCard) would print spade to the console, and control is passed back to the while condition. The value assigned to currentCard is 'spade', so currentCard[0] is 's'. 's' is not equal to 'spade', so we continue the process over, and over, and over… forever.

4 posts were split to a new topic: These exact values will be copied in currentCard, or?

I’m starting to get confused. What’s the main difference between “for” and "while loop?