I dont understand


#1

How come the last line of following code prints " I found a Spade" always?


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('I found a '+ cards[randomNumber]);

Isnt the " randomNumber" only accesible in the while loop function?Also isn’t it random?


#2

The loop will run until it find a spade, it might take 1 attempt, maybe a hundred, but it will find a spade, sooner or later. So at the end of the day, it will always tell you it found a spade

while loop is not a function, its a statement. So unless you use block scope variable (defined with let or const) the variable randomNumber will be global

if we defined var randomNumber in a function, then yes, the scope would have been local.


#3

ah, ok thank you., interesting


#4

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