Dragon Slayer always win with this code?


My code ALWAYS leads to a win, and I am unsure why exactly.

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=1) {
        console.log("It's a hit, well done! You did " + damageThisRound + " damage!");
        if(totalDamage>=4) {
            console.log("The dragon is dead! You have accomplished much! Congrats!!!");
        } else {
    } else {
        console.log("You miss, and the dragon takes advantage of the opportunity to eat you whole!")


= is for assigning/equating. == is for comparison. Check your if statement and see if you are using == instead of =.


Thanks! I found a fix by just removing the =1 entirely, so it looked like if (youHit) but I was still confused why that wouldn't work.


When you do an if statement such as if (youHit=1), it will always evaluate to True because any number that is not 0, is True. Hence why you keep getting the winning message.
youHit=1 means to assign 1 to variable youHit.

If you do if (youHit == 1) or if (youHit === 1) (I forgot which), then you are basically saying if youHit is equal to 1. == or === is for comparison and will produce True or False depending on whether youHit is equal to 1 instead of just True when you do if (youHit = 1).

I hope this clears up the confusion.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.