Setting a variable again?


Why setting the var inside the If statement again?

Actually this is not my code it is the Sample code. I have already set the youHit var to Math.floor(Math.random() *2);
But the sample code in this lesson wants me to state (in the second if/else in the else):
youHit = Math.floor(Math.random() * 2);
I dont understand why i should define this var again to the exact same value it allready has.

var slaying = true;

var youHit = Math.floor(Math.random() *2);
var damageThisRound = Math.floor(Math.random()*5 + 1);
var totalDamage = 0;
while (slaying) {
  if (youHit) {
      console.log("You hit!");
      totalDamage += damageThisRound;
          if (totalDamage >= 4) {
              console.log("You win!");
              slaying = false;
          } else {
              youHit = Math.floor(Math.random() * 2);
  } else {
      console.log("You lose!");
      slaying = false;


youHit can have two values (0 or 1) agree? There is a 50% change that it is a zero, and a 50% change it is a 1.

This way, you have a 50% to hit. You want to update youHit, because the program is still looping, and you want to have a 50% (again) that there is a hit (or no hit), until the dragon is dead, or you miss and you die. Otherwise, the first time would determine if you always hit, or always miss. Bit boring, isn't it?


Okay perfect, got it.
I did not get, that the first time the equation is made the value of the var is set to the outcome forever.
I thought the Value will be re calculated, every time the var is called.

So why is it, that we dont recalculate the stregth of our hit again? ( var damageThisRound = Math.floor(Math.random()*5 + 1); )
What ever strength our first hit has, will be the same for every following hit? is that right?


no, variable will hold there value until you unset them or re-assign them.

Good point, it would make more sense to also recalculate the hit strength. I guess they had to make choices, to make the game not to extensive. (youHit is re-calculated so the dragon has a change of winning), but you can always expand the game after the exercise


Okay Thanks a lot for the super fast Help.
I was really puzzled.