# Gas attack help - JS OR ANY

Hello, does anyone know what is wrong? I’m stuck, help please …

Code:

``````// Calculate the total health of all the ogres.

function sumHealth(enemies) {
// Create a variable and set it to 0 to start the sum.
var totalHealth = 0;
// Initialize the loop index to 0
var enemyIndex = 0;
// While enemyIndex is less than the length of enemies array
while(enemyIndex < enemies.length) {
var enemy = enemies[enemyIndex];
// Add the current enemy's health to totalHealth
totalHealth = enemy[enemyIndex].health;
}
// Increment enemyIndex by 1.
enemyIndex += 1;
}

// Use the cannon to defeat the ogres.
var cannon = hero.findNearest(hero.findFriends());
// The cannon can see through the walls.
var enemies = cannon.findEnemies();
// Calculate the sum of the ogres' health.
var ogreSummaryHealth = sumHealth(enemies);
hero.say("Use " + ogreSummaryHealth + " grams.");
``````

totalHealth should equal enemy[enemyIndex].health plus totalHealth, so instead of an equals sign, you need to add and assign with +=.

In addition, you’re confusing two of your variable names and have left an important statement (incrementing the index) outside the while loop.

``````    while(enemyIndex < enemies.length) {
var enemy = enemies[enemyIndex];
// Add the current enemy's health to totalHealth
totalHealth = enemy[enemyIndex].health;           // You can't index into an enemy! Should either be `enemies[enemyIndex]` or simply `enemy.health`
}
// Increment enemyIndex by 1.
enemyIndex += 1;                                  // If you don't increment the index inside the loop, `enemyIndex` will remain at `0` and you'll loop forever.
``````
1 Like

Thanks a lot! has been fixed !! it was a confusion of both, thanks guys!!

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