How come the last line of following code prints " I found a Spade" always?
var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';
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?
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
const) the variable randomNumber will be global
if we defined
var randomNumber in a function, then yes, the scope would have been local.
ah, ok thank you., interesting
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.