FAQ: Loops - The While Loop

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)];
  console.log(currentCard);
  i++;
}
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.`);

?

2 Likes

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

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)]
console.log(currentCard);
}

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)
console.log(tempNum);
currentCard = cards[tempNum]
console.log(currentCard);
}

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?

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

Thanks.