Brittle morale. Please explain


#1
// You have one arrow. Make it count!

// This should return the enemy with the most health.
function findStrongestEnemy(enemies) {
    var strongest = null;
    var strongestHealth = 0;
    var enemyIndex = 0;
    
    // While enemyIndex is less than the length of enemies:
    while(enemyIndex < enemies.length) {
        var enemy = enemies[enemyIndex];
        if(enemy.health > strongestHealth) {
            strongestHealth = enemy.health;
            strongest = enemy;
        }
        enemyIndex ++;
    }
    return strongest;
}

var enemies = hero.findEnemies();
var leader = findStrongestEnemy(enemies);
if (leader) {
    hero.say(leader);
}

Hey guys. Can someone please explain how does this area work? Thanks!
if(enemy.health > strongestHealth) {
strongestHealth = enemy.health; <---- why do we do that equality
strongest = enemy;
}


#2

If you don’t set the strongestHealth to the enemy’s health then the strongestHealth will stay the same and all the enemies will be strongest and you would have the wrong enemy.


#3

Yes. I see.
But I cant get the logic. How exactly this hapens.


#4

I think it explains it in the hints and in other level’s hints which use arrays, I know ho they work but I think the hints will better explain it.


#5

enemyIndex = 0
strongesthealth = 0

while(enemyIndex < enemies.length)

while(0 is below < number of enemies)
enemy = enemies[enemyIndex] (0)

lets say first monster hp is 10
if 10 is > 0;
strongesthealth become 10.
strongest = enemy (0)

enemyIndex ++
enemyindex iterate from 0 to 1.

while 1 < enemy.length:
enemy = enemies[enemyindex] (1)

lets say enemy1 hp is 20 now.

if 20 (enemy.health) > strongestHealth (10)
yes 20 is > 10.
so strongesthealth become 20
and strongest become enemy(1)

enemyindex ++ enemyindex iterate from 1 to 2.
etc.


#6

Thanks for trying to help! To. make it easier for users to look at the code, please format the code using </> please


#7

Thanks man!!

enemyIndex = 0
strongesthealth = 0

while(enemyIndex < enemies.length)

while(0 is below < number of enemies)
enemy = enemies[enemyIndex] (0)

lets say first monster hp is 10
if 10 is > 0;
strongesthealth become 10.
strongest = enemy (0)

enemyIndex ++
enemyindex iterate from 0 to 1.

while 1 < enemy.length:
enemy = enemies[enemyindex] (1)

lets say enemy1 hp is 20 now.

if 20 (enemy.health) > strongestHealth (10)
yes 20 is > 10.
so strongesthealth become 20
and strongest become enemy(1)

enemyindex ++ enemyindex iterate from 1 to 2.
etc.