Dragon Slaying code questions


In the Dragon Slaying game we set the variable youHit:

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

And this variable should become equal to a random number from 0 to 1(inclusively).
Next, while we're slaying the dragon, we either HIT (true or 1) or MISS (false or 0).

Here's my while statement:

while(slaying) {
if (youHit) {
console.log("You hit!"); }
else {
console.log("You missed!")}

  1. Would it be OK to type while(slaying===1)?
  2. What about random fraction numbers? How does the program make zeros and ones out of them?


  1. No, it's not OK. When you are using boolean variable, there is no need to check if is equal to true/false or 1/0. The variable is true or false and that is enough.



returns a random number between 0 and 1.


the function math.floor will round the number to either 0 or 1 depending on your fraction. i.e. if you get 0.3 from Math.random then it will round to 0; likewise, if you get 0.7 it will round to 1.


I have one question too. What is the difference between if(youHit) and if(youHit === 1) ? Both works fine. As I imagine if (youHit) only checks if it is true, right? and a number 1 stands for a word "true" ?


It's about coding style and writing high quality code. It's redundant code.

The boolean variable has only two possible values - true or false. youHit === 1 will return true. But this is unnecessary, because "youHit" has already the value true. That is all you need.

Also it's easy to forget to write "===" or "==" when you are beginner. If you write only one equal sign like this:

var someBool = false;
if(someBool = true){

that will always return true and will give wrong result.

You can read more posts on this topic here .


I have another question. Exercise says that:

damageThisRound = Math.floor(Math.random()5 + 1) sets damageThisRound to a random number that's between 1 and 5 (up to and including 5).*

But that's not exactly true. If Math.random results '1', then 1*5 = 5, and 5+1 = 6 (and flooring will result the same). So damageThisRound will be a number between 1 and 6, included (not only 1 to 5). Isn't it?


No. Math.random() returns a random number between 0 (inclusive) and 1 (exclusive).


Oh, thanks. I didn't notice that 1 was excluded.

I understand now.


It's my understanding that Math.floor will always round down. That is how you do not end up with a value between 1 and 6, instead a value between 1 and 5 with the statement "var damageThisRound = Math.floor(Math.random()* 5 + 1);"