While loops 1/1


Hi, guys!
Can someone tell me why we set variable coinFace twice, both outside and inside the loop?

var coinFace = Math.floor(Math.random() * 2);

while(coinFace === 0) {
conslole.log ("Heads! Flipping again... ");
var coinFace = Math.floor(Math.random() * 2);
console.log("Tails! Done flipping.");



Try to remove it. And it might give you coinFace is not defined if it does than because of global variable even though while loop doesn’t look like a function you cannot access a variable outside the function unless it’s global variable.


Actually javaScript has the scoping ability only for function not for loops or conditions. The point is that you need an initial guess. Otherwise you’d print either the Heads or Tails message without flipping a coin.

In words its: Flip a coin
if it is heads -> flip again 
if it is heads -> flip again
if it is tails -> tails finally. Done.


It worked well without a global one so was wondering why it was used. Thank you!


Oh you meant why you used var 2 times? Well Idk it is only necessary when you use a variable for the first time and as there is no scoping for while loops it is not necessary here. Is it pre-set by the exercise? Because then it is a bug.


It was used again because it was asked to flip the coin to get the tail and the computer got heads so the function telling the program hey its head flip/choose again using coin Face to get the tail.