Mountain Mercenaries JS Help?

A little help please? When I run this code my hero just runs around collecting coins and summoning new soldiers, but the soldiers never move. When the ogres come they kill all my soldiers and then they kill me. There are no error messages that pop up.

// Gather coins to summon soldiers and have them attack the enemy.
loop {
    // Move to the nearest coin.
    // Use move instead of moveXY so you can command constantly.
    if (enemy) {
        // Loop over all your soldiers and order them to attack.
        var soldiers = this.findFriends();
        var soldierIndex = 0;
        var soldier = soldiers[soldierIndex];
        var enemy = soldier.findNearest(soldier.findEnemies());
        while(soldierIndex < soldiers.length) {
            this.command(soldier, "attack", enemy);
            soldierIndex = soldierIndex + 1;
        }
    } else if (!enemy) {
        var coin = this.findNearest(this.findItems());
        this.move({x: coin.pos.x, y: coin.pos.y});
    }
    
    // If you have funds for a soldier, summon one.
    if (this.gold > this.costOf("soldier")) {
        this.summon("soldier");
    }
        // Use the 'attack' command to make your soldiers attack.
        //this.command(soldier, "attack", enemy);
}

Can anyone tell me why I’m not able to command my soldiers?
Thanks!

Never mind! I figured out what I was doing wrong—I put all my variables in the wrong positions so that “enemy” wasn’t defined and “soldier” wasn’t in the while loop.