Unfunctioning function (js)

I wrote a function to help me tell my soldiers who to attack, but for some reason it’s not working. do you know why?

function toAttack(){
    var w = hero.findByType("warlock");
    var s = hero.findByType("skeleton");
    var m = hero.findByType("munchkin");
    if (w) {
        var wt = hero.findNearest(w);
        return wt;
    if (s) {
        var st = hero.findNearest(s);
        return st;
    if (m) {
        var mt = hero.findNearest(m);
        return mt;

This is because of an error that @xython pointed out (I believe), which is that if you use an if statement on an array, like:
if (w) {
In proper javascript it would return false, and the code wouldn’t run, but in CodeCombat it would still return true even if the w array was empty. Therefore, you need to use len(w), to check if the array has any items inside it.
Also, to prioritise which type of enemy to return you should use else if on the second two statements so that they only run if the statement before them was not true.

@Deadpool198 thank you!
I only saw the message now but I tried it and the code runs smoothly.
Thanks again! :grinning_face_with_smiling_eyes:

1 Like

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