2 while conditions leading to an infinite loop

The first set of codes work fine - I attack the enemy until he’s dead. The second set of codes leads to an infinite loop. I don’t really understand why as the && operator, in my mind, works the same as 2 while conditions (at least that’s how I thought it works with if conditions). Please help explain this to me.

    while (enemy && enemy.health > 0) {
            hero.attack(enemy);        
    }

    while (enemy) {
        while (enemy.health > 0) {
            hero.attack(enemy);
        }
    }

When you kill an enemy - it still exists. if you don’t redefine enemy variable then it still contains a reference to the enemy and not empty. So your outer loop will be eternal. For the first code – it “breaks” by the health condition.

3 Likes