Slaying = false; What is the purpose of this?


Hello people, right what I want to know is why is slaying = false; code used twice in this game? What is purpose for this code, is it to stop the infinite loop?

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 the dragon and did " + damageThisRound + " damage!");
    totalDamage += damageThisRound;
    if (totalDamage >= 4) {
      console.log("You did it! You slew the dragon!");
slaying = false;

} else {
      youHit = Math.floor(Math.random() * 2);
  } else {
    console.log("The dragon burninates you! You're toast.");
    slaying = false;


It is set to false both when you kill the dragon and when you lose to it. For example, if you only set it to false when you kill the dragon, what would happen if you didn't kill it? Your right it would cause an infinite loop if you lost. That works the other way around too. You need it to stop running the function with either outcome.


Yes, exactly :slight_smile: It's there to stop the loop, cause the loop only runs through while slaying equals true. You can code this two different ways: while (slaying === true) or while (slaying). They both mean the same thing, but this exercise has you use the second one.

As for the purpose of slaying = false; being in the code multiple times: You must put that in there to ensure the loop ends. For example: If your code were to say

var number = 10;

while (thisBoolean) {
   if (number < 20) {
      console.log("Your number is less than twenty.");
      thisBoolean = false;
   } else {
      console.log("Your number is greater than twenty.");

The problem with this code simply is: What if your number is greater than twenty? The loop would be infinite, and crash your browser, because thisBoolean still is equal to false. That is why you must use slaying = false; multiple times in your code, cause you could start an infinite loop.


Don't you mean in this sentence -

"The loop would be infinite, and crash your browser, because thisBoolean still is equal to false. "

  • that thisBoolean is still equal to true? It's an infinite loop because the variable would still be true, correct?


Exactly. Sorry for the typo!