J.D. J.D. - 25 days ago 10
Javascript Question

Javascript. Global variable isnt recognized by while loop

My lunch time with Javascript tutorial on codecadamy.com.

I have this simple loop:



var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';

while (currentCard !== 'Spade') {
console.log(currentCard);

var randomNumber = Math.floor(Math.random() * 4);

currentCard = cards[randomNumber];
}

console.log('Found a Spade!');





This goes fine, but if I remove
randomNumber
from loop and place with other global variables, codecademy console doesn't print the result...

Since that global variables should be available to that loop, I assume that something is wrong with codecademy console?

Do you agree that this supposed to work?



var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';
var randomNumber = Math.floor(Math.random() * 4);

while (currentCard !== 'Spade') {
console.log(currentCard);
currentCard = cards[randomNumber];
}

console.log('Found a Spade!');




Answer

By moving the random number outside of your loop it means it is only evaluated once.

So the first time the loop runs, if the random number ends up as any value other than 1, the while loop will run infinitely, because currentCard will always not be equal to 'Spade'.

So what is happening is that the codeacademy console will be evaluationg that loop infinitely, and probably end up crashing.