I'm learning JS in codecademy and it is going very well so far.
But on a particular exercise, there's a step which I can't understand. I solved it and ticked all the 3 exercise steps but the outcome is not what I expected so I was wondering if anybody can help me out?
I'm putting every step of the exercise and then what I've done.
In the end, I'll put what the console logged.
1. Below the cards array, declare a variable, currentCard, with the let keyword but don't assign it a value.
const cards = ['diamond', 'spade', 'heart', 'club'];
// Write your code below
let currentCard;
2. Create a while loop with a condition that checks if the currentCard does not have that value 'spade'. Inside the block of your while loop, add the following line of code:
currentCard = cards[Math.floor(Math.random() * 4)];
Math.floor(Math.random() * 4) will give us a random number from 0 to 3. We'll use this number to index the cards array, and assign the value of currentCard to a random element from that array.
const cards = ['diamond', 'spade', 'heart', 'club'];
// Write your code below
let currentCard;
while ( currentCard != 'spade') {
currentCard = cards[Math.floor(Math.random() * 4)];
}
3. Awesome! Your loop is running, but you can't tell because it doesn't output anything. Let's add a console.log() statement to our while block. Inside the block, after you assign currentCard a new value, log currentCard to the console.
For fun you can run your code a few times and see how the output changes!
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);
}
So this is what the console logged:
heart
club
heart
heart
heart
spade
Every time I log the console the 'spade' appears and the idea is the console not to log 'spade'.
I hope someone can help me out here and happy coding for everyone.
break;somewhere in your loop, it will always finish the current iteration before checking the condition again. If you don't want to log "spade", insertif (currentCard == "spade") break;right after randomly picking one.