While loop for cards


#1

Hello,
I need help understanding this code. I completed the steps however, I'm confused about the output.

This is my output:
Heart
Heart
Diamond
Card is found

Should the output always print 'Heart' & 'Card is found' or should the last code line only print if a certain card is chosen? If so, what changes must I make to my code?

https://www.codecademy.com/courses/learn-javascript/lessons/loops/exercises/while?action=lesson_resume

Here is my code:

var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';
while(currentCard !== 'Spade') {
  console.log(currentCard);
  
  var randomNumber = Math.floor(Math.random() * 3);
  currentCard = cards[randomNumber];
}
console.log('Card is found');

Thanks


#2

It gives numbers in range of [0, 1) (excluding 1)

You can see there are 4 items there, so you need index number 3 too.
Youre multiplying it by 3 that will give ,0,1,2 but not 3.


#3

So it needs to be * 4. Also, what about the last line of code should that always print regards of cards chosen?

Thanks


#4

So it needs to be * 4

Isn't it clear that we have to go over all elements of our Array?
As we have to include all numbers of array. (at index 0, 1, 2, and 3)

what about the last line of code should that always print regards of cards chosen?

The magic is while loops condition. The whole process will keep going on until it finds Spade.


#5

Thanks didn't need the attitude though.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.