# \[Javascript\] Guard Duty

**URL:** <https://discourse.codecombat.com/t/javascript-guard-duty/13938>\
**Category:** Uncategorized\
**Created:** [February 19, 2018, 5:01pm UTC](https://discourse.codecombat.com/t/javascript-guard-duty/13938 "2018-02-19T17:01:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mzz](https://avatars.discourse-cdn.com/v4/letter/m/ea666f/32.png) [@mzz](https://discourse.codecombat.com/u/mzz)\
**Post date:** [February 19, 2018, 5:01pm UTC](https://discourse.codecombat.com/t/javascript-guard-duty/13938/1 "2018-02-19T17:01:16Z")

</div>

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

```python
// 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);

```

---

<div class="post-metadata">

**Author:** ![mzz](https://avatars.discourse-cdn.com/v4/letter/m/ea666f/32.png) [@mzz](https://discourse.codecombat.com/u/mzz)\
**Post date:** [February 19, 2018, 5:11pm UTC](https://discourse.codecombat.com/t/javascript-guard-duty/13938/2 "2018-02-19T17:11:59Z")

</div>

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

```python
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);

```

---

<div class="post-metadata">

**Author:** ![kyay10](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/kyay10/32/7337_2.png) [@kyay10](https://discourse.codecombat.com/u/kyay10)\
**Post date:** [February 21, 2018, 5:49pm UTC](https://discourse.codecombat.com/t/javascript-guard-duty/13938/3 "2018-02-21T17:49:21Z")

</div>

> [@mzz](#):
>
> soldier.distanceTo()

It should be soldier.distanceTo(enemy);

> [@mzz](#):
>
> if (!enemy)

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