Why we have to assign again youHit variable?


#1

Since youHit variable is a global variable why we need to assign again? Can't we call like replacing that line youHit = Math.floor(Math.random() * 2); with just youHit;?

var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0;
while(slaying) {
    slaying = false;
    if(youHit = 1) {
        console.log("You hit the dragon!");
        totalDamage += damageThisRound;
            if(totalDamage >= 4) {
                console.log("The dragon is dead!");
                slaying = false;
            } else {
            youHit = Math.floor(Math.random() * 2);
    } else {
        console.log("The dragon defeated you!");
    }
}

And also why we need that else nested in the second if statement? It's pretty like the primary else statement.
And why we need to input a false assign like this slaying = false; in a if statement. I knew that's only while and for loops can create an infinite looping?


#2

Well Math.random() generates a random number but once you got this number it stays the same. So if you'd use just youHit then it will always have the same value. So to get a new random number you need to call Math.random() again.

Here the position of slaying = false matters. When you have it on the top you always executed this line which leads to the stop of your loop. The idea is something like this:

youHit is true -> deal damage
    damage high enough to kill dragon? -> Yes -> You win->  done
                                                         No -> try to hit again
failed to hit -> fried -> done

So in those cases in which you're done you need the slaying = false and only in those.
I hope this makes sense.


#3

yes thx!...blablabla...........................................................