[Javascript] Guard Duty

Can someone take a look at this and let me know why little buddy is just standing still on my screen:

// Add a soldier to the level to prevent ogres from crossing the path.
// Command the soldier using an event handler function.
function soldierLogic() {
    // Fill in the code for the soldier's actions here.
    // Remember to use 'soldier' instead of 'hero'!
    while (true) {
        var enemy = soldier.findNearestEnemy();
        var distance = soldier.distanceTo();
        // Attack the enemy, if the enemy exists.
        // Units have the attack() method.
        if (enemy && distance < 30) {
            soldier.attack(enemy);
        }    // Else, move back to the starting position.
        else if (!enemy) {
            soldier.move(42, 48);
        }
    }
}
// This assigns your spawned unit to the soldier variable.
var soldier = game.spawnXY("soldier", 42, 48);
// This says to run the soldierLogic function when the soldier is spawned.
soldier.on("spawn", soldierLogic);

I ended up “cheating” and doing this but I am still super bent about what is wrong with the above code…

function soldierLogic() {
    while (true) {
        var enemy = soldier.findNearestEnemy();
        if (enemy) {
            soldier.attack(enemy);
        }
    }
}
// This assigns your spawned unit to the soldier variable.
var soldier = game.spawnXY("knight", 42, 48);
soldier.moveXY(42, 42);
// This says to run the soldierLogic function when the soldier is spawned.
soldier.on("spawn", soldierLogic);

It should be soldier.distanceTo(enemy);

you don’t need to check if there is no enemy, so remove this if statement